O'Reilly logo

Java Extreme Programming Cookbook by Brian M. Coyner, Eric M. Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

assertXXX( ) Methods

Problem

You want to use the various assertXXX( ) methods to test different conditions.

Solution

junit.framework.TestCase, the base class for all test cases, extends from junit.framework.Assert, which defines numerous overloaded assertXXX( ) methods. Your tests function by calling these methods.

Discussion

Table 4-1 summarizes the various assertXXX( ) methods that can be found in junit.framework.Assert. Although you could get by with using assertTrue( ) for nearly every test, using one of the more specific assertXXX( ) methods often makes your tests more understandable and provides good failure messages. This table is only a summary; each of the methods is overloaded as described shortly.

Table 4-1. Assert method summary

Method

Description

assert( )

This was deprecated in JUnit 3.7 because it interferes with the J2SE 1.4 assert keyword. You should use assertTrue( ) instead. This method was completely removed in JUnit 3.8.

assertEquals( )

Compares two values for equality. The test passes if the values are equal.

assertFalse( )

Evaluates a boolean expression. The test passes if the expression is false.

assertNotNull( )

Compares an object reference to null. The test passes if the reference is not null.

assertNotSame( )

Compares the memory address of two object references using the == operator. The test passes if both refer to different objects.

assertNull( )

Compares an object reference to null. The test passes if the reference is null.

assertSame( )

Compares the memory address of two object references using the == operator. The test passes if both refer to the same object.

assertTrue( )

Evaluates a boolean expression. The test passes if the expression is true.

fail( )

Causes the current test to fail. This is commonly used with exception handling, as shown in Recipe 4.13.

Optional first argument

All of the methods in Table 4-1 are overloaded to accept an optional String as the first argument. When specified, this argument provides a descriptive message should the test fail. Here is an example that shows two assert statements, one with the description and one without:

assertEquals(employeeA, employeeB);
assertEquals("Employees should be equal after the clone(  ) operation.",
        employeeA, employeeB);

The second version is preferable because it describes why the test failed, making it easier to fix problems down the road.

Tip

The message should describe what is asserted to be true, rather than what went wrong.

Equality comparison

The assertSame( ) method compares two object references, ensuring that they both refer to the same memory address. assertSame( ) uses the == operator for its comparison. The following two tests are functionally identical:

assertSame("Expected the two parts to be identical.", part1, part2);
assertTrue("Expected the two parts to be identical.", part1 == part2);

While assertSame( ) compares memory addresses, assertEquals( ) compares contents. For objects, this means the .equals( ) method is used instead of ==. assertEquals( ) has numerous overloaded implementations that compare objects to other objects, or primitives to other primitives. Regardless of what you are comparing, the expected value is always listed before the actual value you are testing against. Here are a few examples:

// compare two objects (not using the description argument)
assertEquals(expectedBirthDate, son.getBirthDate(  ));
assertEquals("Garrett", son.getMiddleName(  ));

// compare primitives
assertEquals(50, race.getNumLaps(  ));
assertEquals('a', car.getIdentifier(  ));
assertEquals(expectedByte, customer.getCategory(  ));

JUnit provides special assertEquals( ) methods comparing doubles and floats. These methods accept a delta argument, allowing for rounding off errors. Here is how you can verify that the temperature is 97.1 degrees, accurate to within 0.001 degrees:

assertEquals("Temperature", expectedTemp, actualTemp, 0.001);

Additional examples

Here is how you check for a Boolean condition:

assertTrue("Expected the temperature to be non-negative.", actualTemp >= 0);

Prior to JUnit 3.8, you had to adjust your tests slightly to check for false conditions:

assertTrue("The car should not be running.", !car.isRunning(  ));

JUnit 3.8 added the assertFalse( ) method, making the test more clear:

assertFalse("The car should not be running.", car.isRunning(  ));

Checking for null is easy:

assertNull("Did not expect to find an employee.", 
        database.getEmployee("someInvalidEmployeeId"));

You can also check for non-null values:

assertNotNull("Expected to find an employee with id=" + id, 
        database.getEmployee(id));

And finally, you can explicitly cause a test failure using the fail( ) method:

fail("Unable to configure database.");

See Also

See the JavaDocs for junit.framework.Assert. The methods in Assert are all static, and can be called from other classes. See Recipe 6.3 for an example.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required