繁体   English   中英

在Try..Catch断言中被捕获

[英]Assert in Try..Catch block is caught

刚遇到一些有趣的行为- AssertCatchCatch

List<Decimal> consArray = new List<decimal>();
try
{
    Decimal d;
    Assert.IsTrue(Decimal.TryParse(item.Value, out d));
    consArray.Add(d);
}
catch (Exception e)
{
     Console.WriteLine(item.Value);
     Console.WriteLine(e);
}

Assert抛出AssertFailedException并被catch 一直认为,如果Assert失败,则测试将失败,并且连续执行将中止。 但在那种情况下-测试会继续进行。 如果以后没有发生任何错误-我会通过绿色测试! 从理论上讲-这是正确的行为吗?

编辑:我知道也许是.NET限制以及MsTest中如何进行断言。 断言引发异常。 由于catch捕获其捕获的所有内容,因此会断言断言异常。 但是理论上正确还是MsTest特定?

正如已经回答的那样,这是正确的行为。 你可以改变你的代码通过捕捉AssertFailedException并重新把它扔得到预期的行为。

        List<Decimal> consArray = new List<decimal>();
        try
        {
            Decimal d;
            Assert.IsTrue(Decimal.TryParse(item.Value, out d));
            consArray.Add(d);
        }
        catch (AssertFailedException)
        {
            throw;
        }

        catch (Exception e)
        {
            Console.WriteLine(item.Value);
            Console.WriteLine(e);
        }

您的代码按预期工作。 Assert失败时,将引发从Exception继承的AssertFailedException 因此,您可以添加一个try-catch并捕获它。

在你的情况下,添加一个throw在年底catch并重新抛出异常。

NUnit会做完全相同的事情。 就像我认为的任何其他测试框架一样,但是我只知道C#中的MStestNUnit

我希望您的测试代码不会包含Decimal.TryParse ,但是您的业务逻辑会做到这一点,您将使用对象和方法调用进行测试。

就像是:

var sut = new Sut();
var d = sut.DoSomethingThatReturnsTheDecimal(item.Value);

Assert.AreEqual(0.123, d, string.Format("passed value can not be parsed to decimal ({0})", item.Value);

为了更接近您的实现:

List<Decimal> consArray = new List<decimal>();

Decimal d = Decimal.MinValue;

// You don't need to try-catch a Decimal.TryParse
// Decimal.TryParse(item.Value, out d));

try
{
    d = Decimal.Parse(item.Value)
}
catch
{
    // Handle exception
}

Assert.AreEqual(0.123, d);

// Does the list add anything at all? In this sample it seems a bit redundant
consArray.Add(d);

无论如何,回答您的问题。 try-catch应该捕获您的AssertFailedException

PS:捕获AsserFailedException并将其重新抛出也可以,但是对我来说有点奇怪。 我努力将Assert s保留在任何try-catch块之外。 但这可能只是我的意见,您并没有要求:)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM