Dzi*_*mau 5 c# nunit unit-testing moq
我有一个POCO课程:
public class SomeEntity {
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想在SomeEntity类中使用不同的值测试其他一些类.问题是我需要测试许多属性的不同组合.例如:
所以在每个测试中我想创建这样的测试对象:
// 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);
Run Code Online (Sandbox Code Playgroud)
我不想使用nunit TestCase,因为会有很多组合(巨大的矩阵).
我尝试在调试中运行此测试,它只使用list中的第一个值调用DoSomething一次.
问题:如何结合所有可能的值?
你使用It.IsIn
方法不正确;它仅适用于匹配参数时,即在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);
}
Run Code Online (Sandbox Code Playgroud)
该测试将运行 9 次(2 个参数各 3 条数据,因此 3*3)。请注意,组合是默认值。
但是,如果您只反对结果中的测试数量,那么请专注于您真正想要测试的内容并编写这些测试,而不是用每个可能的值进行猛烈攻击。
归档时间: |
|
查看次数: |
130 次 |
最近记录: |