在Try..Catch断言中被捕获 [英] Assert in Try..Catch block is caught
问题描述
只是遇到了一些有趣的行为-Assert
被Catch
块捕获.
Just came across some interesting behavior - Assert
being caught by Catch
block.
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);
}
声明抛出AssertFailedException
并被catch
捕获.一直认为,如果Assert
失败,则测试将失败,并且连续执行将中止.但在那种情况下-测试会继续进行.如果以后没有发生任何错误-我会得到绿色测试!从理论上讲-这是正确的行为吗?
Assert throws AssertFailedException
and its caught by catch
. Always thought that if Assert
fails then test is failed and consecutive execution is aborted. But in that case - test moves along. If nothing wrong happens later - I get green test! In theory - is it right behavior?
我了解也许是.NET限制以及MsTest中的断言是如何产生的.断言引发异常.由于catch
-捕获了所有捕获的断言异常.但是理论上正确还是MsTest特定?
Edited: I understand that maybe it is .NET restriction and how asserts are made in MsTest. Assert throws exception. Since catch
- catches everything it catches assert exception. But is it right in theory or MsTest specific?
推荐答案
NUnit
将执行完全相同的操作.我认为应该和其他测试框架一样,但是我只知道C#中的MStest
和NUnit
.
NUnit
will do the exact same thing. As should any other test framework I think, but I only know MStest
and NUnit
in C#.
我希望您的测试代码不包含Decimal.TryParse
,但是您的业务逻辑会这样做,您将使用对象和方法调用进行测试.
I'd expect that your test code would not contain Decimal.TryParse
, but your business logic would do that, which you'd test with an object and a method call.
类似的东西:
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);
为了与您的实现更接近一点:
In order to stay a bit closer to your implementation:
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);
无论如何,回答您的问题.尝试捕获应该捕获您的AssertFailedException
.
Anyway, to answer your question. The try-catch is supposed to catch your AssertFailedException
.
PS:捕捉AsserFailedException
并将其重新抛出也可以,但是对我来说有点奇怪.我努力将Assert
放在任何try-catch
块之外.但这可能只是我的意见,您并没有要求:).
PS: Catching the AsserFailedException
and re-throwing it will also work, but it feels a bit strange to me. I'd strive to leave the Assert
s outside any try-catch
blocks. But that might be just my opinion which you didn't ask for :).
这篇关于在Try..Catch断言中被捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!