Summary - Mockito
- Java course
- Advanced
- Lesson 54/82
- 5 min
Combine Mock, when and verify to write a service test.
Summary - Mockito
In this group you saw the core tools of Mockito: mock() for fake objects, @Mock and @InjectMocks for field-based setup, when().thenReturn() for behavior, verify() for interaction checks and ArgumentMatchers for flexible matching.
Now you will combine these into a mini task: building stub and verify logic by hand for an OrderService. This summary shows how mocks really work.
Practice Build a stub for OrderService
Define an OrderService class with a double priceFor(String sku) method that looks up a Map<String, Double> table and returns the price; for an unknown sku it returns 0.0. In an OrderDemo class write main; add put("A1", 9.99) and put("B2", 4.50) to the table; print the result of priceFor("A1").
Starter code
import java.util.*;
// Define the OrderService class (priceFor method uses a Map)
// Write main in OrderDemo; add SKUs to the table and print priceFor's resultSample solution
import java.util.*;
class OrderService {
Map<String, Double> table = new HashMap<>();
double priceFor(String sku) {
return table.getOrDefault(sku, 0.0);
}
}
class OrderDemo {
public static void main(String[] args) {
OrderService s = new OrderService();
s.table.put("A1", 9.99);
s.table.put("B2", 4.50);
System.out.println(s.priceFor("A1"));
}
}Expected output
9.99
Practice Add an interaction counter
Define a new CallTracker class with an int count field and a void record(String sku) method that increments count each call. In a TrackerDemo class write main; call record twice and print count.
Starter code
// Define the CallTracker class (count field and record method)
// Write main in TrackerDemo; call record twice and print countSample solution
class CallTracker {
int count = 0;
void record(String sku) {
count++;
}
}
class TrackerDemo {
public static void main(String[] args) {
CallTracker t = new CallTracker();
t.record("A1");
t.record("B2");
System.out.println(t.count);
}
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is used to define a return value for a mocked method?
- verify
- @Mock
- any()
- when(...).thenReturn(...) Correct answer
Explanation: when(...).thenReturn(...) defines the return value.
2 Match the Mockito summary
| Term | Meaning |
|---|---|
mock() |
Builds a fake object |
@Mock |
Marks a field as mock |
when |
Defines behavior |
verify |
Checks calls |