Search code examples
c#testingbddassertionsmspec

MSpec -> How to verify that a method is called


I'm using MSpec in my Mobile Services application. I want to verify that a method on my custom logger is called when a param passed in is null. Is this possible?

code

if (someOrg == null || target == null) {
    AppUtils.LogInfo(">>>>> +++ Utils-GetAsNeededItems - Null input");
    return null;
}

Solution

  • You can use Moq with MSpec.

    // Mock something
    Mock<ISomething> mock = new Mock<ISomething>();
    
    ClassToTest sut = new ClassToTest();
    sut.WorkMethod(mock.Object);
    
    // Make sure the method TheMethodYouWantToCheck was called
    mock.Verify(m => m.TheMethodYouWantToCheck());
    

    You can also use the overload of Verify and make sure it was called once or at least x time, or at most x times etc.

    mock.Verify(m => m.TheMethodYouWantToCheck(), Times.Once);