C# – Assert in Try..Catch block is caught

assertcmstestunit testing

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?

Best Answer

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