Class org.junit.Assert

JUnit-specific Test Expressions

The Assert class has a bunch of static convenience methods to help you with individual test expressions. For example, without JUnit I might code

    if (obtainedResult == null || !expectedResult.equals(obtainedResult))
        throw new MyTestThrowable("Bad output for # attempt");
With JUnit, you can code
import static org.junit.Assert.*;
...
    assertEquals("Bad output for # attempt", expectedResults, obtainedResults);
The static import statement is not required. It just allows you to code more concisely with assert... instead of Assert.assert.... Every JUnit-supplied assert method throws a java.lang.AssertionErrors when the test fails.

There are lots of assert* methods to take care of the several common Java types. They take care of checking for nulls. Both assert() failures and failure()s (which are effectively the same thing) throw java.lang.AssertionError Throwables, which the test-runners and listeners know what to do with. If a test expression fails, the containing test method quits (by virtue of throwing the AssertionError internally), then the test-runner performs cleanup before executing the next test method in the sequence (with the error being noted for reporting now or later). Take a look at the API spec for org.junit.Assert.

If Assert doesn't supply a specific expression test which you need, then code up your own expression and use Assert.assertTrue() or Assert.assertFalse() on the boolean result of your expression. Or you can just call one of the Assert.fail() methods once you determine a failure case is at hand. If you want to generalize custom failure recognition, you can make your own utility methods or catch blocks which generate and throw a new AssertionError. In this case, you will often want to run initCause() on the AssertionError instance before throwing it, to indicate the original source location of the failure.


$Revision: 2422 $