c# - 使用 Action<T> 模拟方法

标签 c# .net unit-testing mocking moq

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

情况是这样的:

我正在尝试测试一个方法(MethodUnderTest)调用另一个方法(MethodWithAction),它需要Action<T>作为论据。 我想 mock 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;
    }
}

我的测试方法是这样的:

[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);
 }

我想知道 ??? 处发生了什么在测试中,还是有完全不同的方法来解决这个问题?

最佳答案

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

mockObj
    .Setup(m => m.MethodWithAction(It.IsAny<Action<string>>))
    .Callback((Action<string> action) => action(sampleString));

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

关于c# - 使用 Action<T> 模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50586196/

相关文章:

javascript - 没有将 "exportAs"设置为 "ngForm"的指令

java - 清除整个数据库(用于使用 Hibernate 进行单元测试)

c# - 在不打印文档的情况下获取打印页数

c# - 使用 HttpWebrequest/HttpClient 调用 WebApi 2

c# - 新年混沌HackerRank实践题-C#解法优化

c# - 获取 'excelcnv.exe' 位置

c# - 将对象转换到 T

c# - 标签框中的换行符

.net - Linq2XML,为什么 Element()、Elements() 不工作?

javascript - TDD原理,如何让测试失败