gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:29:44 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com