Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up moq and verifying that a method was called

Tags:

c#

.net

tdd

moq

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;

like image 371
dev.e.loper Avatar asked Jan 27 '12 21:01

dev.e.loper


People also ask

How do you know if a mock method is called?

To check if a method was called on a mocked object you can use the Mockito. verify method: Mockito. verify(someMock).

What does Moq verify do?

Verifies that all verifiable expectations have been met.

Can you mock a private method Moq?

Moq supports mocking protected methods. Changing the methods to protected , instead of private , would allow you to mock their implementation.

What is Moq testing framework?

Mocking provides the ability to simulate an object. For example, you can test a call to a database without having to actually talk to it. The Moq framework is an open source unit testing framework that works very well with . NET code and Phil shows us how to use it.


2 Answers

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()); 
like image 93
Michael Liu Avatar answered Sep 30 '22 21:09

Michael Liu


The test is correctly set up.

Check your sut to see if Log.Info actually gets called inside the DoStuffAndLogInfo method.

like image 26
Cristian Lupascu Avatar answered Sep 26 '22 21:09

Cristian Lupascu