I use NMock2, and I've drafted the following NMock classes to represent some common mock framework concepts:
Expect
: this specifies what a mocked method should return and says that the call must occur or the test fails (when accompanied by a call toVerifyAllExpectationsHaveBeenMet()
).Stub
: this specifies what a mocked method should return but cannot cause a test to fail.
So which should I do when?
I'm starting to understand why behavior verification can be just as important as state verification. That is, I now see why we should do 'white box testing' in addition to 'black-box testing.' If I write automated unit tests for a Presenter
in an MVP application, I often need to mock calls to my business layer in order to test the Presenter's methods. For example, I might want to test that the presenter's OnSave
method calls the Business Layer's Save
method, but only when a certain condition is met. After all, the presenter's job is do exactly that: it calls the business layer, it does not perform the save itself. Therefore, I use Expect
to specify what that I want the presenter to call the business layer and conclude my unit test by checking that this was the case using VerifyAllExpectationsHaveBeenMet
.
The problem is, now I feel like I just drank the Kool-Aid and can't see any legitimate use case for Stubbing
interface calls. Often I would love to Stub
these calls and omit the concluding VerifyAllExpectationsHaveBeenMet
(especially because this places a tremendous burden on the test writer to account for all external calls) ... but I can't tell implementation details apart from important testable behavior anymore.
On top of that, when refactoring methods tested with Stub
calls, you risk orphaning those calls, polluting your unit tests and ensuring that heads are scratched forevermore.
How do you decide when to Stub
and when to Expect
?