Simple method object encapsulation of the 'test-for-Exception' scenario (for JUnit).
Used like so:
// the 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
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
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
java.lang.Exception was thrown, the
test 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
java.lang.Exception respects polymorphism,
so you can test that any old
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();
}
}
You might want to compare this class with the
junit.extensions.ExceptionTestCase class.
Note: This class requires JDK 1.4 or higher.
author: Rick Evans author: Juergen Hoeller since: 2.0 |