Leon Mika

Leon Mika

Unit Tests and Verifying Mocks

I’m working with a unit test that uses mocks in which every method in the mock is verified after the method under test is called, even if it is not relevant to the test. Furthermore, the tear down method verifies that every dependent services has no more interactions, which means that removing a verification that is not relevant to the specific test case will cause the test to fail.

Please do not do this. It makes modifying the tests really difficult and results in really long unit tests that hides what the test is trying to assert. It also makes it harder to create new tests to verify a particular behaviour, as you find yourself copying all the verification code that is not relevant to the case that you’re trying to test for.

In my opinion, tests should clearly demonstrate the specific behaviour that you’re trying to verify, and should only include verification of mocks that are directly related to that case. Writing tests that are effectively photo-negatives of the method being tested, one in which the dependent services are verified instead of called, is not a good practice for unit testing.

Instead, have multiple, smaller unit-tests that asserts a particular behaviour, and only verify the mocks that are explicitly required. You gain the coverage by having all these unit tests effectively overlap the various paths a particular method will take. But the important benefit is that it results in more maintainable tests that are easier to work with. That makes it easier to write tests, which means you find yourself doing so more often. Path of least resistance and all that.