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;
To check if a method was called on a mocked object you can use the Mockito. verify method: Mockito. verify(someMock).
Verifies that all verifiable expectations have been met.
Moq supports mocking protected methods. Changing the methods to protected , instead of private , would allow you to mock their implementation.
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.
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());
The test is correctly set up.
Check your sut to see if Log.Info
actually gets called inside the DoStuffAndLogInfo
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With