Moq, strict vs loose usage

I used to use strict mocks when I first starting using mocks in unit tests. This didn’t last very long. There are really 2 reasons why I stopped doing this:

  1. The tests become brittle – With strict mocks you are asserting more than one thing, that the setup methods are called, AND that the other methods are not called. When you refactor the code the test often fails, even if what you are trying to test is still true.
  2. The tests are harder to read – You need to have a setup for every method that is called on the mock, even if it’s not really related to what you want to test. When someone reads this test it’s difficult for them to tell what is important for the test and what is just a side effect of the implementation.

Because of these I would strongly recommend using loose mocks in your unit tests.

Leave a Comment