【问题标题】:How to capture the exception when Assert get failed either in Nunit or MsTest当 Assert 在 Nunit 或 MsTest 中失败时如何捕获异常
【发布时间】:2019-10-07 04:43:33
【问题描述】:

使用 NUnit ir MeTest Assert 方法时如何捕获 Failed Assert 异常消息或状态。

当我的断言失败时,我试图捕获“AssertionException”,我如何使用 NUnit 或 MsTest 捕获它。因为 Assert 方法不返回任何类型。我的要求是即使断言未能完成剩余的断言,测试也应该继续,应该捕获错误并且应该使这个断言失败。我正在使用下面的代码语句。当我使用 Nunit 框架时,它的失败和持续到下一个断言即使我使用 try..catch 块也无法捕获,而在 MsTest 中它失败,使用 try..catch 块捕获并且不继续下一个断言。 非常感谢您的帮助!

    public static void ResponseValueAssert(dynamic actualValue, dynamic expectedValue, string nameOfAssert)
    {
        //var ex = Assert.Throws<AssertionException>(() =>
        //Assert.AreEqual(expectedValue, actualValue, "Actual value doesn't match with Expected value {0}", nameOfAssert));

        if (ResponseValueAssertImplicit(actualValue, expectedValue, nameOfAssert))
        {
            Console.WriteLine("\r\nResponse Assert:- {0}: <PASS>", nameOfAssert);
        }
        else
        {
            Console.WriteLine("\r\nResponse Assert:- {0}: <<FAIL>>", nameOfAssert);

            Console.Error.WriteLine("\r\nResponse Assert:- {0}: <<FAIL>>", nameOfAssert);

            // Assert.Fail();
        }

        Console.WriteLine("Expected Value: {0}.\r\nActual Value: {1}.", actualValue, expectedValue);
    }

    public static bool ResponseValueAssertImplicit(dynamic actualValue, dynamic expectedValue, string nameOfAssert)
    {
        try
        {
            Assert.AreEqual(expectedValue, actualValue, "Actual value doesn't match with Expected value {0}", nameOfAssert);
            return true;
        }
        catch (AssertionException ex)
        {
            return false; 
        }
    }

【问题讨论】:

    标签: nunit mstest


    【解决方案1】:

    将两个完全不同的软件作为一件事提出问题是没有用的。 NUnit 和 MSTest 的答案显然会有所不同,如今它们的实现方式截然不同。

    所以我只回答 NUnit,因为我不知道你会用 MSTest 做什么。

    在 NUnit 中,如果您希望测试继续进行以便在同一个测试中报告多个断言,您可以使用多个断言。那就是……

    Assert.Multiple(() =>
    {
        // Put your various asserts here
    };
    

    NUnit 将报告所有失败的断言。在块的末尾,如果任何一个断言失败,测试将被终止。

    请注意,许多人会说在测试中使用多个断言是一个坏主意。我相信这是大多数时候,但在某些情况下,例如检查同一对象的多个属性,它可能很有用。

    另外,郑重声明,您应该永远不要捕获测试框架内部使用的异常。它们基本上是隐藏的实现细节,您的所有工作都可能在软件的下一个版本中丢失......就像在这种情况下某些人已经发生的那样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      相关资源
      最近更新 更多