Try..Catch块中的断言被捕获

刚刚遇到一些有趣的行为 – 被Catch块捕获的Assert

 List consArray = new List(); 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失败,那么测试失败并且连续执行被中止。 但在那种情况下 – 测试继续进行。 如果以后没有发生任何错误 – 我得到绿色测试! 从理论上讲 – 这是正确的行为吗?

编辑:我明白这可能是.NET限制以及如何在MsTest中进行断言。 断言抛出exception。 因为catch – 捕获它所捕获的一切断言exception。 但理论上是正确的还是具体的MsTest?

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 consArray = new List(); 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块之外。 但这可能只是我的意见,你没有要求:)。

正如已经回答的那样,这是正确的行为。 您可以通过捕获AssertFailedException并重新抛出它来更改代码以获得预期的行为。

  List consArray = new List(); 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失败时,它会抛出一个inheritance自Exception的AssertFailedException 。 所以你可以添加一个try-catch并捕获它。

在你的情况下,在catch的末尾添加一个throw并重新抛出exception。