Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rhino Mocks - AssertWasCalled: How to improve unclear diagnostic message when incorrect arguments

IMHO, Rhino Mocks produces an unclear diagnostic message when AssertWasCalled is used in order to verify that a method has been called with a specific argument.

Example:

interface ISomeInterface
{
    void Write(string s);
}

[TestFixture]
public class SomeTests
{
    [Test]
    public void WriteShouldBeCalledWithCorrectArguments()
    {
        // Arrange
        var mock = MockRepository.GenerateMock<ISomeInterface>();
        var sut = new SomeClass(mock);

        // Act
        sut.DoSomething();

        // Assert
        mock.AssertWasCalled(x => x.Write(Arg<string>.Is.Equal("hello")));
    }
}

Now, if the test fails with this message...

Rhino.Mocks.Exceptions.ExpectationViolationException : ISomeInterface.Write(equal to hello); Expected #1, Actual #0.

... you cannot know if it fails because

A. 'Write' is never invoked -or-
B. 'Write' is in fact invoked but with the incorrect argument

If B would be the cause of the failure then it would be so much clearer if the message would read something like this:

Rhino.Mocks.Exceptions.ExpectationViolationException : ISomeInterface.Write(string arg): Method was called but with the incorrect arguments: Expected: hello, Actual: bye

Can I fix this shortcoming myself (by writing custom matchers for Rhino in some way) or do I simply have to write a manual mock for this?

like image 269
Chris Avatar asked Jan 04 '11 22:01

Chris


1 Answers

I've found a simple solution by using the "Matches" syntax provided by Rhino:

[Test]
public void WriteShouldBeCalledWithCorrectArguments()
{
    // Arrange
    var mock = MockRepository.GenerateMock<ISomeInterface>();
    var sut = new SomeClass(mock);

    // Act
    sut.DoSomething();

    // Assert
    mock.AssertWasCalled(x => x.Write(Arg<string>.Matches(s => Equal(s, "hello"))));
}

private static bool Equal(string s1, string s2)
{
    Assert.That(s1, Is.EqualTo(s2), "Unexpected argument");
    return true;
}

Sure, it's a little clumsy but it gets the job done. If there is a better way of doing it, please let me know.

like image 185
Chris Avatar answered Oct 05 '22 23:10

Chris