C# - 验证模拟 (MoQ) 属性的方法是使用字符串的一部分作为参数调用的

Ash*_*Ash 5 c# unit-testing moq mocking

我正在使用 MoQ 和 C# 来模拟公共属性,我想知道是否使用以特定字符集开头的任何字符串调用了模拟方法之一。

例如,虽然我知道这有效:

mockLogger.Verify(x => x.Information($"Entering {methodName}"), Times.Once);
Run Code Online (Sandbox Code Playgroud)

我正在尝试通过以下尝试来查看是否使用以开头的参数调用mockLoggerInformation()方法$"Exception in {methodName} - Error Message: {ex.Message} - StackTrace:"

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

这不可能吗?或者是否有某种解决方法?

编辑:

我什至试过

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

但它似乎也不起作用。

Luk*_*keW 7

您也可以只使用It.Is<string>()which 可以执行比较。

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

这可能比It.IsRegex()我之前建议的使用更清晰。