【问题标题】:Is it possible to build your TestCaseSource list inside SetUp using NUnit?是否可以使用 NUnit 在 SetUp 中构建您的 TestCaseSource 列表?
【发布时间】:2021-11-11 05:32:20
【问题描述】:

我可以在我的 SetUp 中构建我的 TestCaseData 列表吗?因为有了这个设置,我的测试就被跳过了。其他常规测试运行良好。

[TestFixture]
public class DirectReader
{
    private XDocument document;
    private DirectUblReader directReader;
    private static UblReaderResult result;

    private static List<TestCaseData> rootElementsTypesData = new List<TestCaseData>();

    [SetUp]
    public void Setup()
    {
        var fileStream = ResourceReader.GetScenario("RequiredElements_2_1.xml");
        document = XDocument.Load(fileStream);

        directReader = new DirectUblReader();

        result = directReader.Read(document);

        // Is this allowed?
        rootElementsTypesData.Add(new TestCaseData(result.Invoice.Id, new IdentifierType()));
        rootElementsTypesData.Add(new TestCaseData(result.Invoice.IssueDate, new IdentifierType()));
    }

    [Test, TestCaseSource(nameof(rootElementsTypesData))]
    public void Expects_TypeOfObject_ToBeTheSameAs_InputValue(object inputValue, object expectedTypeObject)
    {
        Assert.That(inputValue, Is.TypeOf(expectedTypeObject.GetType()));
    }
}

【问题讨论】:

    标签: c# unit-testing nunit


    【解决方案1】:

    不,这是不可能的。

    [SetUp] 修饰的方法在每个测试用例之前运行。

    这意味着 NUnit 将首先构建测试用例列表,然后在每个测试用例之前运行 Setup()

    因此,您的 Setup() 永远不会被调用,并且测试用例列表仍然为空。

    【讨论】:

    • 那我应该如何测试result.Invoice.Id 是否是正确的类型?我是否为result.Invoice 中的每个属性创建一个测试?
    • @Jordec 取决于您的目标。您可以只在一个测试用例中测试所有内容。生成错误列表会有点困难;如果您对第一个错误失败感到满意,那就更容易了。
    【解决方案2】:

    正如@IMil 所说,答案是否定的……这是不可能的。

    TestCaseSource 被 NUnit 用来构建要运行的测试列表。它将方法与一组特定的参数相关联。然后,NUnit 会为您的所有测试创建一个内部表示。

    OTOH SetUp(甚至在运行这些测试时使用OneTimeSetUp。到那时,测试的数量和每个测试的实际参数都是固定的,没有什么可以改变它们。

    所以,为了做你想做的事,你的TestCaseSource 必须独立存在,完全确定要用于测试的参数。这就是为什么 NUnit 让您能够将源代码设为方法或属性,而不仅仅是一个简单的列表。

    在你的情况下,我建议......

    private static IEnumerable<TestCaseData> RootElementsTypesData()
    {
        var fileStream = ResourceReader.GetScenario("RequiredElements_2_1.xml");
        document = XDocument.Load(fileStream);
    
        directReader = new DirectUblReader();
    
        result = directReader.Read(document);
    
        yield return new TestCaseData(result.Invoice.Id, new IdentifierType()));
        yield return new TestCaseData(result.Invoice.IssueDate, new IdentifierType()));
    }
    

    显然,这只是“论坛代码”,您必须使用它才能获得实际编译并适用于您的案例的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多