C# 单元测试子方法调用参数

标签 c# unit-testing testing nunit tdd

这是我的 c# 代码。

我不确定应该如何验证使用正确参数调用的 Get 方法。

public class ClassToTest
{    
    public IList<Products> GetProducts(string categoryId)
    {
        var items = _service.Get(new Category { id = categoryId, flag = true });
        return items;
    }
}

例如它是通过 Category 类对象调用的,参数 flagtrueid 已传递。

最佳答案

使用 FakeItEasy 和依赖倒置原理,事情就这么简单:

您的类(class)略有变化:

public class ClassToTest
{
    private readonly IService _service;

    public ClassToTest(IService service) =>
        _service = service;

    public IList<Products> GetProducts(string categoryId) =>
        _service.Get(new Category { id = categoryId, flag = true });
}

public interface IService
{
    IList<Products> Get(Category category);
}

测试:

[Test]
public void Test()
{
    // Arrange
    string categoryId = "categoryId";
    IService service = A.Fake<IService>();
    ClassToTest sut = new ClassToTest(service);

    // Act
    sut.GetProducts(categoryId);

    // Assert
    A.CallTo(() => service.Get(A<Category>.That.Matches(i => i.id == categoryId && i.flag)))
     .MustHaveHappened();
}

[Test]
public void Test()
{
    // Arrange
    string actualId = null;
    bool? actualFlag = null;

    string categoryId = "categoryId";
    IService service = A.Fake<IService>();
    A.CallTo(() => service.Get(A<Category>.Ignored)).Invokes((Category category) =>
      {
          actualId = category.id;
          actualFlag = category.flag;
      });

    ClassToTest sut = new ClassToTest(service);

    // Act
    sut.GetProducts(categoryId);

    // Assert
    Assert.AreEqual(categoryId, actualId);
    Assert.AreEqual(true, actualFlag);
    // optionaly, because it obviously happened
    A.CallTo(() => service.Get(A<Category>.Ignored))
                          .MustHaveHappened();
}

关于C# 单元测试子方法调用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57398950/

相关文章:

testing - 如何从 Robot Framework 中执行 60 天的测试中提取每周报告和日志

java - UNIX/LINUX环境下如何运行testng测试用例

c# - SMTP 中的传递状态通知和已读回执

c# - 如何覆盖在 CaSTLe Windsor 中注册的组件?

java - 测试不通过 Maven 运行?

python - 如何将文件的局部变量导入到当前模块

testing - 如何测试以复杂对象作为参数的 asmx web 服务函数?

c# - 我不太了解 C# 中的转换

c# - 如何在 Visual Studio (C#) 中找到窗体上的控件

c# - 迁移遗留代码时进行单元测试