How to Stub with Conditional Expectations

Conditional Expectations is quite a powerful tool, that allows expectations to act differently according to the arguments passed to the mocked method.

This is very useful for Stubbing methods. Suppose there is a static method Customer.GetAge(string customerName) that needs to be isolated. But the tested code calls GetAge several times with different customerNames.
How can Mocked Customer.GetAge be mocked, to return a different age for each customerName? You guessed correctly Conditional Expectations.

Here is how we can set up GetAge() to return 27 for “Adam” and 22 for “Eve”. 

Mock customerMock = MockManager.Mock(typeof(Customer)); customerMock.AlwaysReturn("GetAge",27).When("Adam"); customerMock.AlwaysReturn("GetAge",22).When("Eve");

Note the usage of When(). This is how Conditional Expectations are invoked. In the above example TypeMock will always return 27 when Customer.GetAge(“Adam”) is called and 22 when Customer.GetAge(“Eve”) is called.

In Natural Mocks our set up will look like this

using (RecordExpectations recorder = RecorderManager.StartRecording()) { Customer.GetAge("Adam"); recorder.Return(27).RepeatAlways.WhenArgumentsMatch(); Customer.GetAge("Eve"); recorder.Return(22).RepeatAlways.WhenArgumentsMatch(); }

You can probably see how using Conditional Expectation will help simplify mocking.

Conclusion

Here are the different ways that expectations can be setup in TypeMock.

  1. Always Expectations:
    Methods mocked with Always will always be mocked, but are not verified (i.e. the method can be called zero or more times)
  2. Invocation Expectations:
    These methods are verified, and must be called for the test to pass
  3. Conditional Always Expectation:
    These Methods will not be verified and will be mocked ONLY when the arguments match those expected. (i.e. the method can be called zero or more times when the arguments match)
  4. Conditional Invocation Expectation
    These Methods are verified and must be called with the correct arguments for the test to pass.

The priorities are 4-3-2-1. So if there is both a Conditional Invocation Expectation (4) and an Invocation Expectations (2), the Conditional Invocation Expectation (4) will be used.

Add Comment

Required fields are marked *. Your email address will not be published.