Search code examples
c#unit-testingmockingmoq

Verify mocked property's method was called with part of string as a parameter


I'm using MoQ and C# to mock a public property and I want to know if one of the mock's methods was called with any strings starting with a particular set of characters.

So for example, while I know this works:

mockLogger.Verify(x => x.Information($"Entering {methodName}"), Times.Once);

I'm trying, with the below attempt, to see if mockLogger's Information() method was called with a parameter starting with $"Exception in {methodName} - Error Message: {ex.Message} - StackTrace:"

mockLogger.Verify(x => x.Information($"Exception in {methodName}: " +
                                         $"Error Message: {exceptionMessage} - " +
                                         $"StackTrace: ........"), Times.Once);

Is this not possible? Or is there some sort of workaround?

Update: I've even tried

mockLogger.Verify(x => x.Information($"Exception in {methodName}: " +
                                         $"Error Message: {exceptionMessage} - " +
                                         $"StackTrace: " + It.IsAny<string>()), 
                                         Times.Once);

but it doesn't seem to work either.


Solution

  • You could also just use It.Is<string>() which can perform a comparison.

    string searchString = $"Exception in {methodName}: " +
                          $"Error Message: {exceptionMessage} - " +
                          $"StackTrace: ";
    mockLogger.Verify(x => x.Information(It.Is<string>(s => s.StartsWith(searchString))), Times.Once);
    

    This is probably a lot clearer than using It.IsRegex() as I suggested previously.