xUnit - How to assert that a call throws an exception

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.

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 I 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.

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.