Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 捕获NUnit AssertionException而不失败C中的测试#_C#_Nunit 3.0 - Fatal编程技术网

C# 捕获NUnit AssertionException而不失败C中的测试#

C# 捕获NUnit AssertionException而不失败C中的测试#,c#,nunit-3.0,C#,Nunit 3.0,所以这是一个有点奇怪的设置。我正在将我们的测试从MSTest(Visual Studio单元测试)转移到NUnit 3+ 在我最初的测试框架中,我添加了一个名为Verify的测试实用程序,在该实用程序中进行了断言,但异常被抑制/忽略,我们只需等到测试结束后再断言是否发生了任何故障 public class Verify { public static int NumExceptions = 0; public static void AreEqual(int expected,

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

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

public static void AreEqual(int expected, int actual) {
    try {
        Assert.AreEqual(expected, actual);
    } catch (AssertionException) {
       NumExceptions++;
    }
}
这不需要对现有测试代码进行实质性更改,也不需要真正更改Verify类的结构。但是,当我在VisualStudio中使用NUnit Adapter执行类似的测试时,第二个测试会按预期运行(不会出现异常),但测试仍然失败,列出了在验证步骤中发现的异常


更广泛的解决方案是简单地删除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的一部分,但是它是公共的,如果您愿意,可以这样使用它

好吧,在这个过程中我确实想到了这一点。我希望有一个“更好”的方法来做这件事。谢谢