【问题标题】:Catch NUnit AssertionException without failing test in C#捕获 NUnit AssertionException 而不会在 C# 中失败测试
【发布时间】:2017-02-15 17:19:47
【问题描述】:

所以这是一个有点奇怪的设置。我正在将我们的测试从 MSTest(Visual Studio 单元测试)转移到 NUnit 3+。

在我最初的测试框架中,我添加了一个名为 Verify 的测试实用程序,其中进行了断言,但异常被抑制/忽略了,我们只需等到测试结束就断言是否发生任何故障。

public class Verify {
    public static int NumExceptions = 0;

    public static void AreEqual(int expected, int actual) {
        try {
            Assert.AreEqual(expected, actual);
        } catch (AssertFailedException) {
           NumExceptions++;
        }
    }

    public static void AssertNoFailures() {
        Assert.AreEqual(0, _numExceptions);
    }
}

所以测试代码可能是:

[TestMethod]
public void VerifyPassesCorrectly() {
    int x = 2;
    int y = 3;

    Verify.AreEqual(3, y);
    Verify.AreEqual(2, x);
    Verify.AreEqual(5, x + y);

    Verify.AssertNoFailures();
}

[TestMethod]
[ExpectedException(typeof(AssertFailedException))]
public void VerifyCountsFailuresCorrectly() {
    Verify.AreEqual(3, 2);
    Assert.AreEqual(1, Verify.NumExceptions);
}

这两个测试都通过了,即使抛出了 AssertFailedException

当我转向 NUnit 时,似乎有更好的方法来解决这个问题(警告,MultipleAssert)。最终,我们将构建新的测试来利用这些改进。但是,与此同时,我需要为现有测试提供一些向后兼容性。

我最初的计划是简单地换出库并更改异常类型:

public static void AreEqual(int expected, int actual) {
    try {
        Assert.AreEqual(expected, actual);
    } catch (AssertionException) {
       NumExceptions++;
    }
}

这不需要对现有测试代码进行实质性更改,也不需要对 Verify 类的结构进行真正的更改。但是,当我在 Visual Studio 中使用 NUnit Adapter 执行这样的测试时,第二个测试会按预期运行(不会出现异常),但仍然无法通过测试,列出在验证步骤中发现的异常。

更广泛的解决方案是简单地删除 Verify 类,因为 NUnit 不再需要它。但在此之前,有没有办法在 Verify 中使用 NUnit API,这样 Verify 类中的断言就不会被 NUnit“存储”并导致测试失败?

【问题讨论】:

    标签: c# nunit-3.0


    【解决方案1】:

    您将无法告诉 NUnit 断言不应该以某种方式使测试失败。所以,你可以做的就是改变你的 AreEqual 方法来自己做相等性测试。

    if (expected != actual) {
      NumExceptions++;
    }
    

    这似乎是最简单的解决方案。

    第二种选择是完全按照 NUnit 在其 Assert 语句中所做的事情。如果你想做 that (但当然不会导致测试失败)。代码如下所示:

    public static void AreEqual(int expected, int actual) {
        var equalToConstraint = Is.EqualTo(expected);
        var result = equalToConstraint.ApplyTo(actual);
        if (!result.IsSuccess) {
            NumExceptions++;
        }
    }
    

    Is 类是 NUnit 的一部分,但它是公共的,如果你愿意,你可以像这样使用它。

    【讨论】:

    • 好的,我在完成这个过程时确实发生了这种情况。我希望可能有一种“更好”的方式来做到这一点。谢谢!
    猜你喜欢
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 2012-06-10
    • 1970-01-01
    • 2011-04-24
    • 2023-01-20
    • 2017-05-05
    相关资源
    最近更新 更多