如何故意使所有 C# 单元测试失败

How to intentionally fail all C# unit tests

问题:

我正在尝试找出是否有一种方法可以在满足特定条件时使所有 C# 单元测试失败。

背景:

我为编码和解码其内部数据的对象设置了单元测试。这是一个相当人为的例子:

[TestClass]
public class FooTests
{
    private Foo TestFoo { get; set; }

    [TestMethod]
    public void DataEncodingIsWorking()
    {
        // TestFoo.EncodeData() ...
    }

    [TestMethod]
    public void DataDecodingIsWorking()
    {
        // TestFoo.DecodeData() ...
    }

    public FooTests(dynamic[] data) {
        TestFoo = new Foo(data);
    }
}

public class Foo {

    public void EncodeData() {
        // encodes Foo's data
    }

    public void DecodeData() {
        // decodes Foo's encoded data
    }

    public Foo(dynamic[] data) {
        // feeds data to Foo
    }
}

我没有在每个 [TestMethod] 中创建一个新的 TestFoo 实例(有些重复),而是在 FooTests 中创建了一个全局 TestFoo 对象。如果 TestFoo 无法实例化,我希望所有 FooTests 单元测试都失败(因为如果对象无法实例化,encoding/decoding 将无法工作)。

这实际上不是最佳实践的问题,但我也很好奇这种方法是否糟糕。我想另一种方法是设置一个额外的单元测试来查看 TestFoo 是否正确实例化。

How to intentionally fail all C# unit tests


TL;DR: 在您的 ClassInit() 中,实例化测试所需的任何对象并添加适当的 Assert 语句。如果任何条件失败,所有测试都将失败。


您可以添加一个在任何测试方法 运行 之前自动调用的方法,并用 ClassInitialize 属性修饰它。

MSDN:

Identifies a method that contains code that must be used before any of the tests in the test class have run and to allocate resources to be used by the test class. This class cannot be inherited.

...和:

When run in a load test, the method marked with this attribute will run once, and any initialization operations it performs will apply to the entire test. If you need to do initialization operations once for every virtual user iteration in the test, use the TestInitializeAttribute.

在下面的示例中,我们实例化了一个新的 Foo 对象并且 Assert 它不是 null。我们当然可以根据需要测试其他情况。

[ClassInitialize]
public void ClassInit(TestContext context)
{
    TestFoo = new Foo(dynamicDataFromContext);
    Assert.IsNotNull(TestFoo);
}

如果您对数据驱动的测试感兴趣,那么您可能想要查看How To: Create a Data-Driven Unit Test

我认为 CRice makes 在这个页面上关于 Assert.Inconclusive() 所以你也可以选择合并它。

抛出异常将使测试失败。或者你可以调用 Assert.Fail().

在测试前提条件失败的情况下,最好是Assert.Inconclusive()。这样你的测试将停止(橙色)但不会失败(红色) - 不确定状态表示不满足测试先决条件并且你永远不会断言你正在尝试测试的情况。