Verifying arguments passed into a mocked or stubbed method can help you write more specific, robust unit tests. This is easily accomplished with Rhino Mocks by using Constraints.
As an example, let’s write a test for the function MyClass.MyMethod in the code below:
public interface IMyDependency { void DependencyMethod(MyResult myResult); } public class MyResult { public int Code; } public class MyClass { public IMyDependency MyDependency { get; set; } public MyClass(IMyDependency myDependency) { MyDependency = myDependency; } public void MyMethod(string input) { switch (input) { case "A": MyDependency.DependencyMethod( new MyResult { Code = 1 }); break; case "B": MyDependency.DependencyMethod( new MyResult { Code = 2 }); break; default: break; } } }
The first thing we need to do is create a mock IMyDependency and verify that its DependencyMethod is called, so let’s do that:
[TestMethod] public void MyMethodTest() { // Arrange var mockMyDependency = MockRepository.GenerateMock(); var target = new MyClass(mockMyDependency); mockMyDependency.Expect( x => x.DependencyMethod(Arg<MyResult>.Is.Anything)); const string input = "A"; // Act target.MyMethod(input); // Assert mockMyDependency.VerifyAllExpectations(); }
This test passes, but how do we know the argument with the correct value was used? We can modify our mock object’s Expect call to use argument constraints to do this!
mockMyDependency.Expect( x => x.DependencyMethod(Arg<MyResult>.Matches(arg => arg.Code.Equals(1))));
Now my test only passes when the mock is called with an argument that matches the specified criteria. This is obviously a very basic example, but the fact that you can pass a delegate or derive a custom class from Rhino Mocks’s AbstractConstraint class makes this a very powerful feature.