Spring JUnit test to assert test for exceptions
Posted by davidnewcomb on 14 Oct 2008 in Techie
When writing unit tests you often need to check to see if a method throws a particular type of exception under a particular set of conditions.
In the package
org.springframework.test
there is a handy helper class to help you do this.
new AssertThrows(NumberFormatException.class)
{
public void test() throws Exception
{
Integer.parseInt("not a number");
}
}.runTest();
The constructor takes the class type of the exception that is expected when the test is performed. If the test()
method does not throw an exception of that type runTest()
throws an exception.
One of the nice things about this test is that it honours the polymorphic class structure, so the test will pass if any (inherited) child of the named exception is thrown.
For example:
new AssertThrows(Exception.class)
{
public void test() throws Exception
{
Integer.parseInt("not a number");
}
}.runTest();
is equivalent.No feedback yet
Form is loading...