Rhino Mocks – using AssertWasCalled on Common.Logging ILog.Debug

common.loggingnetrhino-mocksspring.netunit testing

I'm having trouble using Rhino Mocks to assert that a method was called (and ideally with a particular parameter). The Method is ILog.Debug(FormatMessageHandler) in Common.Logging 2.0 using the new lamba syntax. It works fine using the old way plain ILog.Debug(string).

    // Sample Code to Test
    public int TestFuncLambda(ILog log, int a, int b)
    {
        log.Debug(m => m("TestFunc START"));

        int c = a + b;

        log.Debug(m => m("TestFunc END"));

        return c;
    }

    public int TestFunc(ILog log, int a, int b)
    {
        log.Debug("TestFunc START");

        int c = a + b;

        log.Debug("TestFunc END");

        return c;
    }

    [TestMethod]
    public void Should_log_start_TestFuncLamba()
    {
        var logger = MockRepository.GenerateMock<ILog>();

        logger.Stub(x => x.IsDebugEnabled).Return(true);

        TestFuncLambda(logger, 1, 2);

        // Doesn't work, says zero calls plus I'm not sure how to check for the word "START" in the string either
        logger.AssertWasCalled(x => x.Debug(Arg<FormatMessageHandler>.Is.Anything), o => o.IgnoreArguments());
    }

    [TestMethod]
    public void Should_log_start_TestFunc()
    {
        var logger = MockRepository.GenerateMock<ILog>();
        logger.Stub(x => x.IsDebugEnabled).Return(true);

        TestFunc(logger, 1, 2);

        // Works fine
        logger.AssertWasCalled(x => x.Debug(Arg<string>.Matches(Text.Contains("START"))));
    }

Best Answer

I'm going to assume here that you are just tinkering with Rhinomocks, and this has nothing to do with the logging framework, is that correct? I say this because there are no concrete implementations in your tests, only mocks.

Without testing your code, this line looks like it will always be zero:

logger.AssertWasCalled(x => x.Debug(Arg<FormatMessageHandler>.Is.Anything), o => o.IgnoreArguments());

because your actual method TestFunc() passes strings to log.Debug, and not a FormatMessageHandler:

So it would make sense that the number of calls is zero. Add a line to TestFunc() like this:

log.Debug(new FormatMessageHandler());

and see if that fixes it.