views:

30

answers:

2

I'm using Rhino Mocks to expect a call. There is a single parameter which is a string. But I'm not bothered about the case of the string. I want the test to pass even if the case is wrong. So I'm doing the following:

//expect log message to be called with a string parameter.  
//We want to ignore case when verifiyig so we use a constraint instead of a direct parameter
Expect.Call(delegate { logger.LogMessage(null); }).Constraints(Is.Matching<string>(x => x.ToLower()=="f2"));

It seems a bit log winded. Is there a more sensible way of doing this?

A: 
// arrange
var loggerStub = MockRepository.GenerateStub<ILogger>();

// act
loggerStub.LogMessage("f2");

// assert
loggerStub.AssertWasCalled(
    x => x.LogMessage(Arg<string>.Matches(
        s => string.Equals(s, "f2", StringComparison.OrdinalIgnoreCase)
    ))
);

If you don't care about parameters but just the method call:

loggerStub.AssertWasCalled(
    x => x.LogMessage(null),
    x => x.IgnoreArguments()
);
Darin Dimitrov
I think he wants to verify the string, but doesn't care about case. Neither one of these does that.
tvanfosson
Correct, I've updated my answer.
Darin Dimitrov
+1  A: 

I would use the AAA format that @Darin suggests (or similar). I think it's more concise, but you'll still have to use the same basic constraint for case insensitive matching, I think. A helper method can make this more readable.

 private bool CaseInsensitive( string s, string t )
 {
      return string.Equals( s, t, StringComparison.OrdinalIgnoreCase );
 }

 var loggerMock = MockRepository.GenerateMock<Logger>();

 loggerMock.Expect( l => l.LogMessage( Arg<string>.Matches( s => CaseInsensitive( s, "f2" ))));

 classUnderTest.MethodUnderTest();

 loggerMock.VerifyAllExpectations();
tvanfosson