Search code examples
c#unit-testingmoqmstest

Assert with the parameter that contains string


I am using MSTest and Moq to write unit tests. I want to test that a method is called with the string parameter that contains sub-string.

_mockMessageService.Verify(x => x.ShowMessage(It.IsAny<string>()), Times.Once());

In above code, I can verify that ShowMessage method was called once with some string parameter but I want to make sure that string contain words like success, fail, partially success etc. I can't directly pass entire string because it is not consistent, only part of it is consistent. Is it possible?


Solution

  • It.Is<>() allows for a predicate to be used to verify the parameter

    _mockMessageService.Verify(x => x.ShowMessage(It.Is<string>(s => 
        s.Containes("success", StringComparison.InvariantCultureIgnoreCase) || 
        s.Containes("fail", StringComparison.InvariantCultureIgnoreCase) ||
        s.Containes("partially success", StringComparison.InvariantCultureIgnoreCase)
    )), Times.Once());
    

    Reference: MOQ Quickstart - Matching Arguments