A different approach to Mock Verification

Scott Bellware has posted about the awkwardness of mock testing – I find that the syntaxes for mock frameworks feel awkward to me.

It is true that the Validation of calls and arguments are hidden in the setup part of the test and the verification is run automatically at the end of the test. Here is how you can have a more explicit validation using TypeMock. (Note: I am using the Generic Syntax of our coming version)

Implicit Validation 

[Test] public void SomeTest() { // mock next instance of TestedClass this happens in SomeObject.DoYourThing(); Mock m = Mock<TestedClass>.MockNextInstance(); // mock foo once m.ExpectAndReturn("foo", "yada yada"); // do our thing SomeObject test = new SomeObject(); test.DoYourThing(); // verify that foo was called once m.Verify(); }

Explicit Validation

[Test] public void SomeTest() { // mock next instance of TestedClass this happens in SomeObject.DoYourThing(); Mock m = Mock<TestedClass>.MockNextInstance(); // mock foo m.AlwaysReturn("foo", "yada yada"); // do our thing SomeObject test = new SomeObject(); test.DoYourThing(); // verify that foo was called once Assert.AreEqual(1, m.GetCallCount("foo")); }

There are 2 differences:

1. Using AlwaysReturn instead of ExpectAndReturn, this turns the mock into a stub.

2. Fetching and Asserting the amount of calls made, after the test for our verification.

 

Notice how using a remark solves Scott’s problem altogether

 

The downfall for using the explicit syntax are:

1. No Fast Fail – Using the explicit syntax we will not fail fast when foo was called twice (or with wrong arguments) that could lead to another failure in the test (as the code continued to run)

2. Concurrent Tests, We can’t use the concurrent features of Mocking (using VerifyWithTimeout) that enables testing multithreaded code without playing with joining threads  (just wait for a particular method in one thread to be called to signal that we can validate some data in the test thread)

2 comments
  1. I think the challenge here is that the method name is represented as a string. If there’s no alternative to this then it would be an annoying hindrance to refactoring.

Add Comment

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