Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a unit test confirm an exception has been thrown

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?

like image 985
Richard Avatar asked May 25 '11 13:05

Richard


People also ask

How do you test an exception in unit testing?

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.

How do I test exceptions in JUnit 5?

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.

Should JUnit test throw exception?

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.

How do you handle exceptions in unit test Python?

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.


2 Answers

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.

like image 134
Jon Skeet Avatar answered Nov 01 '22 13:11

Jon Skeet


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

like image 27
abatishchev Avatar answered Nov 01 '22 13:11

abatishchev