C# – Setting up moq and verifying that a method was called

cmoqnettdd

Using Microsoft Test Framework and Moq I'm trying to verify if a log4net method was called.

    [TestMethod()]
    public void Log_Info_When_Stuff_Is_Done()
    {
        SampleClass sampleObject = new SampleClass(); 

        Mock<log4net.ILog> logMockObject = new Mock<log4net.ILog>();

        sampleObject.Log = logMockObject.Object;

        sampleObject.DoStuffAndLogInfo();

        logMockObject.Verify(moqLog => moqLog.Info("do stuff got called"), Times.AtLeastOnce());

    }

I get an exception on Verify call saying that

Expected invocation on the mock at least once, but was never
performed: moqLog => moqLog.Info("do stuff got called") No setups
configured. No invocations performed.

What am I doing wrong?

update the problem was with a getter for SampleClas.Log property. I was always returning LogManager.GetLogger(...); even when the property was already set to a ILogProxy. I was under impression that the property's get accessor won't be called because I've set up a proxy like so sampleObject.Log = logMockObject.Object;

Best Answer

Right now Moq is verifying that DoStuffAndLogInfo calls Info with the exact string "do stuff got called". If it's actually calling Info with a different argument, and you don't care what the actual argument is, use the following instead:

logMockObject.Verify(moqLog => moqLog.Info(It.IsAny<string>()), Times.AtLeastOnce());