Test if exception is thrown within NUnit 3

If you want to test your code indeed throws an exception within a certain position, NUnit provides possibilities to test if indeed an exception is thrown. Before NUnit 3 you simply added the attribute ExpectedException(typeof()) as the following example shows:

[ExpectedExeption(typeof(ArgumentException))]
public void TestMethod()
{ ... }

Within Nunit 3 this isn’t possible anymore. You don’t have to use the attribute anymore, but can use the following kind of code within your unit test:

Assert.That(() => <method>, Throws.Typeof<typeof_exception>);

Or

Assert.That(() => <method>, Throws.Typeof.typeof_exception);
Posted in Unit testing by Bruno at August 1st, 2017.

Leave a Reply