Returning Values
When a mocked method has a return value, it is necessary to fake
that value (because the original method is not actually called). You
can return different values and verify that the code works
properly in different scenarios.
Example - Returning Values
Let us suppose the Logger class from the First Mock topic returns a value (true or false) and that IsAuthenticated behaves differently with different return values (this is an hypothetical test to make a point).
Here is a code snippet of how we can do this by changing the code at position 2 and using ExpectAndReturn.
// C#
[Test] public void Authenticated ()
{
Authentication authenticator = new Authentication();
MockManager.Init ();
// the Logger class is now being mocked
1 Mock logMock = MockManager.Mock(typeof(Logger));
// set up our expectations
2 logMock.ExpectAndReturn("Log",true);
logMock.ExpectAndReturn("Log",false);
Assert.IsFalse(authenticator.IsAuthenticated("user","password"));
MockManager.Verify();
}
' Visual Basic
<Test()> Public Sub Authenticated ()
Dim authenticator As Authentication = new Authentication
MockManager.Init()
' the Logger class is now being mocked
1 Dim logMock As Mock = MockManager.Mock(GetType(Logger))
' set up our expectations
2 logMock.ExpectAndReturn("Log",True)
logMock.ExpectAndReturn("Log",False)
Assert.IsFalse(authenticator.IsAuthenticated("user","password"))
MockManager.Verify()
End Sub
In the above we instructed the mocked Log method to return true the first time and false the second time.
Copyright © Typemock Ltd. 2004-2010. All Rights Reserved.