Test doubles
Replacing a dependency during a test: the five test doubles (dummy, stub, spy, mock, fake), programming an answer, verifying an interaction, and deciding what to double or leave real, with Mockito.
- 24 cards
- 4 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
A few cards from the deck
Test double: what is it?
Show the answer
An object built for a test, which stands in for a real dependency of the code under test.
You replace a slow, random or uncontrollable dependency (network, clock, payment) so the test is fast and reproducible. There are five kinds of doubles.
What is
cin this test?
```java
Depot depot = mock(Depot.class);
Client c = depot.trouver(42);`null- An empty
Client, built by the default constructor - Nothing: the line throws a
MockitoExceptionbecause no answer is programmed - The real customer number 42, read from the real database by the double
Show the answer
nullAn unprogrammed Mockito mock returns the type's default value:
nullfor an object, 0 for an integer, an empty list for a list. It never runs the real code and throws nothing.A … is used to control what the code under test receives; a … is used to check what the code under test sends.
Show the answer
A stub is used to control what the code under test receives; a mock is used to check what the code under test sends.
Both replace a dependency, but in opposite directions: the stub feeds the code, the mock observes its outputs.
Dummy: what is it?
Show the answer
A double passed only to fill a required parameter, and which the test never uses.
A constructor that requires a service a test never calls gets a dummy (
nullor an empty double): it only serves to make the code compile.Every refactoring breaks about thirty tests, even though the application's behaviour does not change. These tests use verify on the order and number of each internal call. What is the cause?
- They freeze the way things are done, not the observable result
- Mocks are slower than stubs and trigger random failures
- Mockito is incompatible with refactoring and needs a newer version
- End-to-end tests are missing that would cushion internal changes
Show the answer
They freeze the way things are done, not the observable result
A mock that checks every internal call ties the test to the code's structure. Refactoring changes that structure without changing behaviour, and the test breaks anyway. Use verify only for exchanges visible from outside (a mail sent).