-
Notifications
You must be signed in to change notification settings - Fork 3
Resetting Call Metrics
There are certain scenarios whereby you need to share your mocks between tests. All calls to mocked methods and properties are recorded so verification checks can be made. When sharing mocks, this behaviour is not desirable as the visit counts will not match your expected across tests.
In these situations you may wish to use the static method Mock.CallGroup which takes a list of mock objects. This method returns an object that implements IDisposable making it ideal to use inside a using block:
[TestMethod]
public async Task AuthenticateUserReturnsValidTrueForKnownUser()
{
using (Mock.CallGroup(_mockDataService, _mockSettingsService))
{
var authenticatedUserResult = await _authenticationService.AuthenticateUser("TestUser", "TestPassword");
_mockDataService.Verify(s => s.GetUserByUsernameAndPassword(
"TestUser", "TestPassword"), Occurred.Once());
_mockSettingsService.VerifySet(s => s.CurrentUser, Occurred.Once());
Assert.IsTrue(authenticatedUserResult);
}
}
Above you will see that this test contains a call to authenticate a user with a username and password and verifies that certain mock methods are called. The _mockDataService and _mockSettingsService are static variables, and are created in a static method marked with the [ClassInitialize] attribute along with the AuthenticationService instance itself.
The using block will reset all the visit counts on the mock objects so subsequent checks in this or other tests in this test class will also work.
Note: This currently is not thread-safe so these sort of tests are not suitable for running in parallel.