The First Mock (Using Attributes)
This topic describes how to use Typemock Isolator attributes to simplify test writing with mocks. We will be using the same example as in the First Mock topic.
The [ClearMocks] attribute will clear all mocks without validating them.
The [VerifyMocks] attribute on a test method will validate the mocks.
When a test fails, Typemock Isolator will only clear the mocks and rethrow the test failure.
When the attribute decorates the test class, ALL test methods of that class are verified.
The verification process should always be performed before clearing the expectations (in fact, calling Verify() clears the expectation as well). Failing to do so will cause the tests to pass without actually going through the verification process.
Example - Using Attributes
// C#
[TestFixture]
[ClearMocks] // Clear all mocks between tests
public class TestClass
{
[Test]
[VerifyMocks] // Verify all mocks after tests
public void Authenticated ()
{
Authentication authenticator = new Authentication();
// the Logger class is now being mocked
Mock logMock = MockManager.Mock<Logger>();
// set up our expectations for 2 Log calls in IsAuthenticated
// 1) "Entering Authentication" Log at first line
// 2) "User login failed user" Log
logMock.ExpectCall("Log");
logMock.ExpectCall("Log");
// authentication should fail
Assert.IsFalse(authenticator.IsAuthenticated("user","password"));
// Verify is done automatically by the framework.
}
}
' Visual Basic
<TestFixture()> _
<ClearMocks()> _ ' Clear all mocks between tests
Public Class TestClass
<Test()> _
<VerifyMocks()> _ ' Verify all mocks after tests
Public Sub Authenticated ()
Dim authenticator As Authentication = new Authentication
' the Logger class is now being mocked
Dim logMock As Mock = MockManager.Mock(Of Logger)
' set up our expectations for 2 Log calls in IsAuthenticated
' 1) "Entering Authentication" Log at first line
' 2) "User login failed user" Log
logMock.ExpectCall("Log")
logMock.ExpectCall("Log")
' authentication should fail
Assert.IsFalse(authenticator.IsAuthenticated("user","password"))
' Verify is done automatically by the framework.
End Sub
EndClass
Copyright © Typemock Ltd. 2004-2010. All Rights Reserved.