CuriousGeorge CuriousGeorge - 2 months ago 4x
C# Question

C#: How do I check "no exception occurred" in my unit test?

I'm writing a unit test for this one method which returns "void". I would like to have one case that the test passes when there is no exception thrown. How do I write that in C#?


(My guess is this is how I should check, but what goes into "???")

I hope my question is clear enough.


Your unit test will fail anyway if an exception is thrown - you don't need to put in a special assert.

This is one of the few scenarios where you will see unit tests with no assertions at all - the test will implicitly fail if an exception is raised.

However, if you really did want to write an assertion for this - perhaps to be able to catch the exception and report "expected no exception but got this...", you can do this:

public void TestNoExceptionIsThrownByMethodUnderTest()
    var myObject = new MyObject();

    catch (Exception ex)
        Assert.Fail("Expected no exception, but got: " + ex.Message);

(the above is an example for NUnit, but the same holds true for MSTest)