Strict Mocking - hypersolutions/hypermock GitHub Wiki

Strict Mocking

The default behaviour of the Mock.Create class is to generate a loose mock. This is defined as a mock that will return defaults for calls that do not have a setup. This is fine in most circumstances, however it can lead to false positives in certain scenarios. Typically functions that are not setup to return anything would return there default value such as false for Booleans or null for objects. These can cause branches in your code to processed where you might not have intended.

In these situations you may wish to use the overload on the Mock.Create to define the strict behaviour. This means that any call to a mock method, function or property must be satisfied by an intended mock setup. For example:

[TestMethod]
public void ManageDisablesAccountUsingStrictSetup()
{
    var mockService = Mock.Create<IAccountService>(MockBehavior.Strict);
    mockService.SetupSet(s => s.HasAccounts).SetValue(false);
    var controller = new AccountController(mockService.Object);

    controller.Manage(false);

    mockService.VerifySet(s => s.HasAccounts, false, Occurred.Once());
}

If the above did not contain the line to set the mock when the behaviour is set to strict then a StrictMockViolationException would be thrown. In a loose mock scenario this would not be the case and the test would pass.