Question

I am using MSTest and in a [TestMethod] I have an object whose code throws an exception and I catch it; in certain circumstances, I re-throw it, other times I don't, but the test always fails indicating that the exception was thrown, even though I do not re-throw it some times. How do I conditionally ignore an exception? Because it is conditional, whether or not I re-throw the exception, I can't use [ExpectedException].

Was it helpful?

Solution

You should be testing your method in deterministic circumstances, i.e. with a set of arguments that always returns the same response. If your method sometimes throws an exception and sometimes doesn't, you should have one test for the cases where it throws, and another for when it doesn't.

If you do not have control over the conditions for which you throw an exception, it is a sign that you need to refactor your code so that you extract the condition, and are able to test the method in a deterministic way.

For example:

[TestMethod]
public void SomeMethodDoesntFail()
{
    var obj = new objectUnderTest();
    var shouldThrow = false;
    var result = obj.SomeMethod(shouldThrow);
    Assert.IsEqual(*expected result*, result);
}

[TestMethod, ExpectedException]
public void SomeMethodFails()
{
    var obj = new objectUnderTest();
    var shouldThrow = true;
    var result = obj.SomeMethod(shouldThrow);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top