c# - 在 C# 中捕获 NUnit AssertionException 而不会导致测试失败

标签 c# nunit-3.0

所以这是一个有点奇怪的设置。我正在将我们的测试从 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 时,似乎有更好的方法可以解决这个问题(Warn、MultipleAssert)。最终,我们将构建新的测试来利用这些改进。然而,与此同时,我需要为现有测试提供一些向后兼容性。

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

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

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

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

最佳答案

您将无法告诉 NUnit 断言不应以某种方式导致测试失败。因此,您可以做的就是更改 AreEqual 方法,以便自己进行相等测试。

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

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

第二个选项是完全按照 NUnit 在其 Assert 语句中所做的操作。如果您想这样做(但当然不会导致测试失败)。代码如下所示:

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

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

关于c# - 在 C# 中捕获 NUnit AssertionException 而不会导致测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42256116/

相关文章:

c# - 如何在 C# 中将文本与列表框中的 ITEMS 进行比较

c# - JWT header 算法 : is "hs256" the same as "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"

c# - Visual Studio : Exclude Project by default when running tests from test explorer

c# - 将 Visual Studio 文件夹结构导出到 Excel

c# - 在C#中,如何在编译时限制谁可以调用方法

visual-studio-2017 - VS 2017 测试资源管理器窗口空引用异常

c# - ASP.Net Core 2.0 SignInAsync返回异常值不能为null,提供程序

teamcity - 如何在 TeamCity 9.x 中安装 nUnit 3 nunit3-console.exe

c# - 如何进行批量更新?