verify
- Java course
- Advanced
- Lesson 52/82
- 5 min
Learn call verification with verify.
verify
With verify(mock) you check the calls made on a mock. You can test whether a specific method was called with a specific input, and how many times.
service.register("Alex");
verify(repo).save(any(User.class));
verify(mail, times(1)).send("Alex");This is how you verify the side effects of the code under test. The interaction is checked, not the return value. Qualifiers like times, never, atLeast specify the frequency.
Call count qualifiers
With verify you can also check the call count. times(n) means exactly n times, never() means never, atLeast(n) means at least n times.
verify(mail, times(2)).send("Alex");
verify(repo, never()).delete(anyInt());
verify(logger, atLeast(1)).info(anyString());This verifies that side effects happen with exactly the expected frequency. Errors such as duplicate emails or accidental deletes are caught. Tests become more precise.
Practice Count interactions with a Logger
Define a Logger interface (void info(String msg)). A Counter class tracks the number of info calls. In Counter the log(String msg) method increments the counter each call. In a VerifyDemo class write main; call log three times and print the counter.
Starter code
// Define the Logger interface (info method)
// Define the Counter class (tracks info call count)
// Write main in VerifyDemo; call log three times and print the counterSample solution
interface Logger {
void info(String msg);
}
class Counter implements Logger {
int count = 0;
public void info(String msg) {
count++;
}
}
class VerifyDemo {
public static void main(String[] args) {
Counter c = new Counter();
c.info("a");
c.info("b");
c.info("c");
System.out.println(c.count);
}
}Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does verify check?
- The mock's return value
- The test duration
- The mock's type
- The calls made on the mock Correct answer
Explanation: verify checks the calls made on the mock.
2 Match the qualifiers
| Term | Meaning |
|---|---|
times(2) |
Exactly two times |
never() |
Never called |
atLeast(1) |
At least once |
atMost(3) |
At most three times |
3 Complete the verify call
service.register("Ayşe");
____(mail).send("Ayşe");
service.register("Ayşe");
verify(mail).send("Ayşe");
Explanation: answer: verify. when defines behavior, mock builds the object.