ORIGINAL TECHNICAL PRACTICE
Test behavior rather than implementation
How would you test a function that groups and sorts customer events without making the tests depend on its internal data structure?
Written for independent practice. The model answer presents one approach; clarify constraints and explain alternatives.
A REASONED APPROACH
Model answer.
Specify externally visible behavior: valid inputs, ordering, duplicate handling, empty results and errors. Assert outputs and invariants rather than the choice of map, loop or sorting helper.
Work through it
- Create small examples that isolate one rule, including ties and missing optional fields. Use deterministic identifiers so failures remain understandable.
- Add invariants such as every retained event appearing exactly once and timestamps being ordered within each group. Compare against a simple trusted reference on small generated inputs.
- Include negative cases for invalid input only when rejection is part of the API contract. If mutation is forbidden, explicitly assert that the input remains unchanged.
Tradeoffs to discuss
- Example tests communicate intent; property-based tests explore combinations. Neither substitutes for a clearly defined contract or for realistic integration checks at system boundaries.
Common pitfalls
- A test that repeats the production algorithm can repeat its bug. Mocking every dependency may conceal incorrect serialization, ordering or storage behavior.