A year ago I made a post on the absence of the DoesNotThrow assertion in xUnit. In this post I show how you can assert if a method actually throws an exception. xUnit is a popular testing framework for C# and .Net.
You can check if a method call throws an exception by using the Assert.Throws method from xUnit. This can be seen below:
Assert.Throws<Exception>(() => SomethingThatThrowsAnException());
If the method SomethingThatThrowsAnException()
from the above throws an exception the assertion passes, if it does not throw an exception, the assertion will fail and thereby the test fails. It is as simple as that.
If you wish to check the exception that is thrown you can easily get that. It is returned when Assert.Throws
is called:
var exception = Assert.Throws<Exception>(() => SomethingThatThrowsAnException());
Assert.Equal("Exception!", exception.Message);
In the above we check if the message of the exception matches the string "Exception!"
. As mentioned in my previous post I find it odd that there is no DoesNotThrow method on Assert. The argumentation for this is that the unit test will fail if an exception is thrown and is unhandled. You can think about this as if all tests have a "hidden" DoesNotThrow wrapped around them.
An alternative is to use Record.Exception()
:
var exception = Record.Exception(() => callYourMethod());
Check if a specific exception is thrown
You can check that the type of the exception is the expected one, by using IsType<yourType>
:
Assert.IsType<yourexception>(exception);
This way you can can check the type of the exception that is thrown.
That is all!
I hope these were the code snippets you were looking for, if you think something is missing on this page, please let me know in the comments down below.