class under test public class Foo { public void someBusinessLogic(String name) { if (name == null) { throw new IllegalArgumentException("The 'name' argument is required"); } // rest of business logic here... } } The test for the above bad argument path can be expressed using the {@link AssertThrows} class like so:
public class FooTest { public void testSomeBusinessLogicBadArgumentPath() { new AssertThrows(IllegalArgumentException.class) { public void test() { new Foo().someBusinessLogic(null); } }.runTest(); } }
This will result in the test passing if the
Foo.someBusinessLogic(..)
method threw an {@link java.lang.IllegalArgumentException}; if it did not, the test would fail with the following message:
"Must have thrown a [class java.lang.IllegalArgumentException]"
If the
wrong type of {@link java.lang.Exception} was thrown, thetest will also fail, this time with a message similar to the following:
"junit.framework.AssertionFailedError: Was expecting a [class java.lang.UnsupportedOperationException] to be thrown, but instead a [class java.lang.IllegalArgumentException] was thrown"
The test for the correct {@link java.lang.Exception} respects polymorphism,so you can test that any old {@link java.lang.Exception} is thrown like so:
public class FooTest { public void testSomeBusinessLogicBadArgumentPath() { // any Exception will do... new AssertThrows(Exception.class) { public void test() { new Foo().someBusinessLogic(null); } }.runTest(); } }
Intended for use with JUnit 4 and TestNG (as of Spring 3.0). You might want to compare this class with the {@link junit.extensions.ExceptionTestCase} class.
@author Rick Evans
@author Juergen Hoeller
@since 2.0
@deprecated favor use of JUnit 4's {@code @Test(expected=...)} support