使用 Action<T> 模拟方法

Anj*_*wal 3 .net c# unit-testing moq mocking

我是单元测试的新手,很高兴知道我是否犯了任何错误或没有朝着正确的方向前进。

这是情况:

我正在尝试测试一个方法(MethodUnderTest),它调用另一个作为参数的方法(MethodWithActionAction<T>。我想模拟MethodWithAction,但根据返回值测试逻辑。

这是结构:

interface IInterface
{
    void MethodWithAction(Action<string> action);
}

class MyClass : IInterface
{
    public void MethodWithAction(Action<string> action)
    {
        string sampleString = "Hello there";
        action(sampleString);
    }
}

class ClassUnderTest
{
    public IInterface Obj = new MyClass();
    public string MethodUnderTest()
    {
        string stringToBeTested = string.Empty;

        Obj.MethodWithAction(str =>
        {
            if (str.Contains("."))
                stringToBeTested = string.Empty;
            else
                stringToBeTested = str.Replace(" ", string.Empty);
        });
        return stringToBeTested;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的测试方法是这样的:

[TestMethod]
[DataRow("Hello, World", "Hello,World")]
[DataRow("Hello, World.","")]
[DataRow("Hello", "Hello")]
public void MethodUnderTestReturnsCorrectString(string sampleString, string expected)
{
    var mockObj = new Mock<IInterface>();
    mockObj.Setup(m=>m.MethodWithAction(It.IsAny<Action<string>>))
    .Callback(???);
    ClassUnderTest sut = new ClassUnderTest();
    sut.Obj=mockObj.Object;
    string actual = sut.MethodUnderTest();
    Assert.Equal(expected, actual);
 }
Run Code Online (Sandbox Code Playgroud)

我想知道???在测试中发生了什么,或者对于这个问题是否有完全不同的方法?

Nko*_*osi 6

获取在回调中传递给模拟的操作参数,并使用示例字符串调用它。

mockObj
    .Setup(m => m.MethodWithAction(It.IsAny<Action<string>>))
    .Callback((Action<string> action) => action(sampleString));
Run Code Online (Sandbox Code Playgroud)

参考Moq Quickstart以更好地了解如何使用此模拟框架。