In my previous post, Testing for exceptions in C#, I mentioned how to create an Assert Extension class to check that an exception is thrown, much like in NUnit.
You can also create a method to test that an exception isn’t thrown, be it a general or specific exception. NUnit includes such a method and in the interest of completion I will give an example.
Most of the time though, you should only be testing for the correct behavior or testing that a specific exception is being raised.
Almost every case where people are looking to test that a specific exception isn’t thrown can be changed and the changed tests will end up delivering better value.
With that out of the way, here is how you would implement it:
public static void DoesNotThrows<T>(Action expressionUnderTest, string exceptionMessage = "Expected exception was thrown by target of invocation.") where T : Exception { try { expressionUnderTest(); } catch (T) { Assert.Fail(exceptionMessage); } catch (Exception) { Assert.IsTrue(true); } Assert.IsTrue(true); }
Here is how you would use it:
// Testing that no exception is being thrown [TestMethod] public void ExampleDoesNotThrows() { int someInteger = 10; AssertExtension.DoesNotThrows<Exception>(() => someInteger.ToString()); } // Testing that correct behavior will not throw an exception [TestMethod] public void ExampleDoesNotThrowsNoException() { // Arrange var classUnderTest = new StringlyType(); classUnderTest.Setup(); int toStringlyfy = 1; // Act && Assert AssertExtension.DoesNotThrows<NullReferenceException>(() => classUnderTest.Stringlyfy(toStringlyfy)); } // Testing that another exception than the one we expected isn't thrown [TestMethod] public void ExampleDoesNotThrowsWithSpecificType() { // Arrange var classUnderTest = new StringlyType(); int toStringlyfy = 1; // Act && Assert AssertExtension.DoesNotThrows<IndexOutOfRangeException>(() => classUnderTest.Stringlyfy(toStringlyfy)); }
You can refer to this previous post for more context on the test methods.
A DoesNotThrows method could be used to replace a test that does not have any asserts and whose only way of failing is through raising an exception.
In any case, when you are about to use a DoesNotThrows, stop and really think it through.
Good post for someone with advanced knowledge of Exception handling and Test.
If anyone wants to read basics of Exception handling in C# check:
Exception handling in C# (With try-catch-finally block details)
Thanks