DuckQueen
DuckQueen

Reputation: 802

How to exit test with failer even if there is catch around it?

Problem is: I need to exit test with fail message. using Microsoft.VisualStudio.TestTools.UnitTesting Assert.Fail("message"); gets caught via try catch. What can be done to exit test with failer that would not be catchable?

Say my test has something like this inside: ...remoteServerEventHandler(e => /*some logic */ Assert.Fail("message")) yet it gets handeled via serverEventHandler while I just want to exit with failure in my test.

Upvotes: 0

Views: 193

Answers (2)

Torbjörn Kalin
Torbjörn Kalin

Reputation: 1986

Check the type of exception and rethrow it if it is an assertion exception.

try
{
    // ...
    Assert.Fail("message");
    // ...
}
catch (Exception ex)
{
    if (ex is AssertFailedException)
    {
        throw;
    }
}

The code assumes you are using MSTest. Change AssertFailedException to AssertionException if you are using NUnit.

Upvotes: 1

Akshay
Akshay

Reputation: 1901

In catch block, at the end you should write throw, which will re-throw the same exception in calling function or to the next block executing.

Upvotes: 1

Related Questions