Reputation: 315
Is it necessary to verify the interactions with the Mock objects? So let's say I have a class:
Class A{
B b;
public A(B b){
this.b = b;
}
int getObjectFromDatabase(int id){
Object o = b.get(id);
// do some extra work
return result
}
}
Now I'm testing the getObjectFromDatabase
method. I have passed the Mock object of Class B. Do I need to verify the interaction that b.get(id)
is being called or not? Or is it a good idea to just check the input and output result I get?
Upvotes: 3
Views: 1209
Reputation: 95704
In general, verifying that a stubbed call happened is not necessary, and leads to brittle tests (tests that fail even when the implementation remains correct). In your case, it probably doesn't matter whether get(id)
is called, or how many times; it only matters that the object returned is correct, and it's likely that a correct result will require calling b.get(id)
at some point.
Mockito has some explicit advice in its verify(T)
Javadoc:
Although it is possible to verify a stubbed invocation, usually it's just redundant. Let's say you've stubbed foo.bar(). If your code cares what foo.bar() returns then something else breaks(often before even verify() gets executed). If your code doesn't care what get(0) returns then it should not be stubbed. Not convinced? See here.
Though it may make sense to verify(b).get(id)
a certain number of times (including zero) when testing caching or lazy-load behavior, or in other circumstances where the interaction is a crucial part of the tested behavior, strive to test for the correct output/state instead of verifying your expected interactions.
Upvotes: 5