我有一个 POCO 类:
public class SomeEntity {
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
我想在 SomeEntity 类中使用不同的值测试其他一些类。问题是我需要测试许多属性的不同组合。例如:
- Id = 1,FirstName = null,LastName = "Doe"
- Id = 1, FirstName = "", LastName = "Doe"
- Id = 1, FirstName = "John", LastName = "Doe"
- Id = 1,FirstName = null,LastName = ""
- 等等
所以在每个测试中我都想像这样创建测试对象:
// 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 的 ValuesAttribute
和 ValueSourceAttribute
是为了。
关于您因为组合太多而反对使用 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/