Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert in Try..Catch block is caught

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

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?

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?

like image 524
nikita Avatar asked Feb 15 '13 06:02

nikita


1 Answers

As already answered, this is correct behavior. You can change your code to get Your expected behavior by catching the AssertFailedException and re-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);
        }
like image 66
Peter Henell Avatar answered Oct 12 '22 07:10

Peter Henell