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

后端 未结 6 1994
再見小時候
再見小時候 2020-12-30 18:34

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 t

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-30 18:50

    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)

提交回复
热议问题