如何在Nunit或MsTest中Assert get失败时捕获异常

如何在Nunit或MsTest中Assert get失败时捕获异常,nunit,mstest,Nunit,Mstest,如何在使用NUnit ir MeTest Assert方法时捕获失败的Assert异常消息或状态 当我的断言失败时,我正试图捕获“AssertionException”,如何使用NUnit或MsTest捕获它。因为Assert方法不返回任何类型。我的要求是,即使assert get未能完成剩余的断言,测试也应该继续,应该捕获错误并使该断言失败。我在使用下面的代码语句。当我使用Nunit框架时,即使我使用try,也无法捕捉到它的失败和持续性。。catch块,如MsTest中所示,它失败了,使用tr

如何在使用NUnit ir MeTest Assert方法时捕获失败的Assert异常消息或状态

当我的断言失败时,我正试图捕获“AssertionException”,如何使用NUnit或MsTest捕获它。因为Assert方法不返回任何类型。我的要求是,即使assert get未能完成剩余的断言,测试也应该继续,应该捕获错误并使该断言失败。我在使用下面的代码语句。当我使用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; 
        }
    }
公共静态void ResponseValueAssert(动态actualValue、动态expectedValue、Assert的字符串名)
{
//var ex=Assert.Throws(()=>
//AreEqual(expectedValue,actualValue,“实际值与预期值{0}”不匹配,Assert的名称);
if(ResponseValueAssertImplicit(实际值、预期值、资产名称))
{
WriteLine(“\r\n应答断言:-{0}:”,资产名称);
}
其他的
{
WriteLine(“\r\n应答断言:-{0}:”,资产名称);
Console.Error.WriteLine(“\r\n应答断言:-{0}:”,资产名称);
//Assert.Fail();
}
WriteLine(“预期值:{0}。\r\n实际值:{1}.”,实际值,预期值);
}
公共静态bool ResponseValueAssertImplicit(动态actualValue、动态expectedValue、Assert的字符串名)
{
尝试
{
AreEqual(expectedValue,actualValue,“实际值与预期值{0}不匹配”,Assert名称);
返回true;
}
catch(AssertionException-ex)
{
返回false;
}
}

将两个完全不同的软件作为一件事来提问是没有用的。对于NUnit和MSTest来说,答案显然是不同的,它们现在的实现方式非常不同

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

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

Assert.Multiple(()=>
{
//把你的各种主张放在这里
};
NUnit将报告所有失败的断言。在块结束时,如果任何断言失败,测试将终止

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

另外,为了记录在案,您应该永远不要捕获测试框架内部使用的异常。它们基本上是隐藏的实现细节,您的所有工作都可能在下一版本的软件中丢失……在本例中,有些人已经遇到过这种情况