Im writing a unit test for a c# class, One of my tests should cause the method to throw an exception when the data is added. How can i use my unit test to confirm that the exception has been thrown?
assertRaises(exception, callable, *args, **kwds) The test passes if the expected exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception.
In JUnit 5, to write the test code that is expected to throw an exception, we should use Assertions. assertThrows(). In the given test, the test code is expected to throw an exception of type ApplicationException or its subtype. Note that in JUnit 4, we needed to use @Test(expected = NullPointerException.
The JUnit TestRunners will catch the thrown Exception regardless so you don't have to worry about your entire test suite bailing out if an Exception is thrown. This is the best answer.
There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.
It depends on what unit test framework you're using. In all cases you could do something like:
[Test]
public void MakeItGoBang()
{
Foo foo = new Foo();
try
{
foo.Bang();
Assert.Fail("Expected exception");
}
catch (BangException)
{
// Expected
}
}
In some frameworks there's an attribute you can add to the test method to express the expected exception, or there may be a method, such as:
[Test]
public void MakeItGoBang()
{
Foo foo = new Foo();
Assert.Throws<BangException>(() => foo.Bang());
}
It's nicer to limit the scope like this, as if you apply it to the whole test, the test could pass even if the wrong line threw the exception.
[ExpectedException(typeof(System.Exception))]
for Visual Studio Unit Testing Framework.
See MSDN:
The test method will pass if the expected exception is thrown.
The test will fail if the thrown exception inherits from the expected exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With