How do I check “no exception occurred” in my MSTest unit test?

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:

[Test]
public void TestNoExceptionIsThrownByMethodUnderTest()
{
    var myObject = new MyObject();

    try
    {
        myObject.MethodUnderTest();
    }
    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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)