Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Verify mocked (MoQ) 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?

EDIT:

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.

like image 650
Ash Avatar asked Aug 31 '16 04:08

Ash


1 Answers

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.

like image 107
LWood Avatar answered Oct 14 '22 04:10

LWood