Assembler in Try..Catch block caught

I just came across some interesting behavior - Assert , which got into the 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 throws and catch it on Catch . It has always been believed that if Assert fails, the test fails and sequential execution is interrupted. But in this case, the test passes. If nothing bad happens later, I get the test green ! In theory, is this the right behavior?

Edited: I understand that perhaps this is a limitation of .NET and as stated in MsTest. The exception is fixed. Because Catch - catches everything that catches the assert exception. But is this correct in theory or specifically in MsTest?

+8
c # assert unit-testing mstest
source share
3 answers

NUnit will do the same. Like any other test environment, I think, but I only know MStest and NUnit in C #.

I would expect your test code to not contain Decimal.TryParse , but your business logic will do this, which you would check with an object and a method call.

Something like:

 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); 

To get a little 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); 

In any case, to answer your question. AssertFailedException -catch is AssertFailedException catch your AssertFailedException .

PS: Capturing an AsserFailedException and AsserFailedException will also work, but for me it is a bit strange. I would try to leave Assert out of any try-catch blocks. But this can only be my opinion, which you did not ask for :).

+4
source share

As already mentioned, this is the correct behavior. You can modify your code to get the expected behavior by catching an AssertFailedException and throwing it.

  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); } 
+6
source share

Your code is working properly. When Assert does not work, it throws an AssertFailedException , which inherits from Exception . That way you can add try-catch and catch it.

In your case, add throw at the end of catch and throw the exception.

+5
source share

All Articles