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

后端 未结 6 1997
再見小時候
再見小時候 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条回答
  •  暖寄归人
    2020-12-30 18:48

    In NUnit, you can use:

    Assert.DoesNotThrow(); 
    

    to assert that your code does not throw an exception. Although the test would fail if an exception is thrown even if there was no Assert around it, the value of this approach is that you can then distinguish between unmet expectations and bugs in your tests, and you have the option of adding a custom message that will be displayed in your test output. A well-worded test output can help you locate errors in your code that have caused a test to fail.

    I think it's valid to add tests to ensure that your code is not throwing exceptions; for example, imagine you are validating input and need to convert an incoming string to a long. There may be occasions when the string is null, and this is acceptable, so you want to ensure that the string conversion does not throw an exception. There will therefore be code to handle this occasion, and if you haven't written a test for it you will be missing coverage around an important piece of logic.

提交回复
热议问题