当测试装置的设置代码需要在不违反最佳实践的情况下进行自我测试时,我们可以采取哪些可能的方法来处理这种情况?

问题描述 投票:0回答:1

当测试装置的设置代码需要在不违反最佳实践的情况下进行自我测试时,我们可以采取哪些可能的方法来处理这种情况?考虑 C# 12.0/.NET 8.0 和 NUnit 中的以下代码(但答案可能适用于大多数测试框架和编程语言):

// Usings and namespace have been abbreviated away.

[TestFixture]
public class Foo
{
    private Bar? _bar;
 
    [SetUp]
    public void Setup()
    {
        _bar = DoApiRequest("endpoint"); // The problem here is that the API request needs to be tested itself, also this can be anything, not just an API request.
        // ...
    }
    // Other tests
    // ...
}

我们可以尝试在设置中添加断言:

// Usings and namespace have been abbreviated away.

[TestFixture]
public class Foo
{
    private Bar? _bar;
 
    [SetUp]
    public void Setup()
    {
        _bar = DoApiRequest("endpoint"); // The problem here is that the API request needs to be tested.
        // Assert code here which makes the setup basically a test itself that other tests depend on.
        // ...
    }
    // Other tests
    // ...
}

但我听说这是一种非常糟糕的做法。

c# unit-testing testing automated-tests nunit
1个回答
0
投票

我只是用断言创建测试:

[Fact]
public void TestSetup()
{
    // Test the API request that needs to be tested.
    // Assert.Something(_bar)
}

© www.soinside.com 2019 - 2024. All rights reserved.