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

时间:2016-08-31 04:39:35

标签: c# unit-testing mocking moq

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

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

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

我尝试通过以下尝试,尝试使用以mockLogger

开头的参数调用Information()的{​​{1}}方法
$"Exception in {methodName} - Error Message: {ex.Message} - StackTrace:"

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

编辑:

我甚至尝试过

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

但它似乎也无效。

5 个答案:

答案 0 :(得分:3)

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

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

这可能比我之前建议的使用It.IsRegex()要清楚得多。

答案 1 :(得分:1)

您无需在验证中检查完全匹配,您可以查找字符串的一部分,例如:

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

答案 2 :(得分:1)

您可以使用Regex执行此操作。可以将字符串与将{rempx作为参数的It.IsRegex()方法进行比较。

一个例子是

string regexString = "" //Substitute for actual regex to search what you want
mockLogger.Verify(x => x.Information(It.IsRegex(regexString)), Times.Once);

以下来自Moq&#39; quickstart的代码示例显示它在设置中使用,但它也适用于验证:

// matching regex
mock.Setup(x => x.DoSomething(It.IsRegex("[a-d]+", RegexOptions.IgnoreCase))).Returns("foo");

答案 3 :(得分:0)

另一种可能性是使用Callback方法。 Callback方法可以接收用于调用模拟方法的参数,因此可以执行您需要的自定义验证。例如:

[TestMethod]
public void VerifyWithCallback()
{
    // Arrange
    bool startsWith = false;
    const string methodName = "methodName";
    Mock<ILogger> mockLogger = new Mock<ILogger>();
    SomeClassWithLogger cut = new SomeClassWithLogger { Logger = mockLogger.Object };
    mockLogger.Setup(l => l.Information(It.IsAny<string>())).Callback<string>(s =>
    {
        startsWith = s.StartsWith("Entering starts with test");
    });

    // Act
    cut.Logger.Information($"Entering starts with test {methodName}");

    // Assert
    Assert.IsTrue(startsWith);
}

答案 4 :(得分:-1)

我相信moq文档在验证属性时使用VerifySet()方法。看看这里:https://github.com/Moq/moq4/wiki/Quickstart

相关问题