c# - 如何使用 It.IsIn(someRange) 对多个字段迭代 POCO 属性的组合?

标签 c# unit-testing nunit moq

我有一个 POCO 类:

public class SomeEntity {
  public int Id { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

我想在 SomeEntity 类中使​​用不同的值测试其他一些类。问题是我需要测试许多属性的不同组合。例如:

  1. Id = 1,FirstName = null,LastName = "Doe"
  2. Id = 1, FirstName = "", LastName = "Doe"
  3. Id = 1, FirstName = "John", LastName = "Doe"
  4. Id = 1,FirstName = null,LastName = ""
  5. 等等

所以在每个测试中我都想像这样创建测试对象:

// test that someOtherObject always return the same result 
// for testObject with ID = 1 and accepts any values from range of 
// values for FirstName and LastName

var testObject = new SomeEntity {
  Id = 1, // this must be always 1 for this test
  FirstName = It.IsIn(someListOfPossibleValues), // each of this values must be accepted in test
  LastName = It.IsIn(someListOfPossibleValues) // each of this values must be accepted in test
}

var result = someOtherObject.DoSomething(testObject);

Assert.AreEqual("some expectation", result);

我不想使用 nunit TestCase,因为会有很多组合(巨大的矩阵)。

我尝试在调试中运行此测试,它仅使用列表中的第一个值调用 DoSomething 一次。

问题:如何遍历所有可能值的组合?

最佳答案

您错误地使用了 It.IsIn;它仅用于 matching arguments 时使用,即在 Verify 调用中检查一个值是否在一组可能的值中,或者在 Setup 调用中控制 Moq 的响应方式。它不是设计用于以某种方式生成一组测试数据。这正是 NUnit 的 ValuesAttributeValueSourceAttribute是为了。

关于您因为组合太多而反对使用 NUnit,是因为您不想编写所有组合还是因为您不想进行那么多测试?如果是前者,则使用 NUnit 的属性和 CombinatorialAttribute让 NUnit 完成创建所有可能测试的工作。像这样:

[Test]
[Combinatorial]
public void YourTest(
    [Values(null, "", "John")] string firstName, 
    [Values(null, "", "Doe")] string lastName)
{
    var testObject = new SomeEntity {
        Id = 1, // this must be always 1 for this test
        FirstName = firstName,
        LastName = lastName
    };

    var result = someOtherObject.DoSomething(testObject);

    Assert.AreEqual("some expectation", result);
}

该测试将运行 9 次(2 个参数各有 3 条数据,所以 3*3)。请注意,组合是默认值。

但是,如果您只反对结果中的测试数量,那么请专注于您实际想要测试的内容并编写这些测试,而不是用每个可能的值来进行测试。

关于c# - 如何使用 It.IsIn(someRange) 对多个字段迭代 POCO 属性的组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34639590/

相关文章:

c# - 获取参数使用 FromUri 并验证此参数

c# - 如何在 Nunit 中使用文件断言并检查文件是否存在

macos - 如何从终端在 Mac 上运行 fsharp 测试?

c# - 使用 NUnit 引擎时如何解决错误 "Unable to acquire remote process agent"

c# - Gmap.Net route 的点之间没有线条

c# - 新行、默认字体和大小(打开 xml sdk)

C# 返回 ConcurrentBag 的副本

c# - 了解一些单元测试实践

php - makePartial() 返回 Mockery\Exception\BadMethodCallException : Method does not exist on this mock object

java - 如何模拟或以其他方式测试 readPassword?