Reputation: 7859
Using Mockito for testing, I can easily unit tests this method:
public void doTheDog() {
// Some code
extObj.executeDog();
}
I will simply verify that executeDog() has been called:
verify(extObj).executeDog();
However when I have a very long and convoluted method, this is not always as easy.
public void doTheDog() {
// Very long code
extObj.bark();
// Very long code
extObj.walk();
}
The above method will still behave as a dog, even if I remove bark(). So it doesn't make much sense to test for it:
verify(extObj).bark();
After mocking, there isn't something that really tells me if the code works fine!!!
End of the story. Now I have to write unit tests for code that is for the most like the long-and-convoluted code above. What can I do to write good unit tests anyway with mocking?
Upvotes: 1
Views: 428
Reputation: 95644
As mpkorstanje began in the comments, a good unit test should verify that the behavior of a given unit matches the spec as tightly and concisely as possible.
It sounds like part of the problem here is that your spec isn't clearly defined: dog.bark()
is important enough to happen, but not important enough to be specified or tested. If you feel the method is long and convoluted, the best solution is to refactor the method into small, clear, testable pieces and then test those individually. This will likely also make them easier to work with in your actual production systems.
All that said, Mockito is designed for flexible tests, as compared to replay-based mocking systems: It is entirely your choice whether to verify(dog).bark()
, or you can choose whether or not exact quantity atLeastOnce()
or order (see InOrder) matters. Generally speaking, shoot to specify as little as possible, so that your tests will pass for any working implementation or change in your actual system.
Upvotes: 1