Java Reference
In-Depth Information
@Test
public void testStringEquals() {
String michael = "Michael";
String michael2 = michael;
String michael3 = new String("Michael");
String michael4 = "Michael";
assertTrue(michael == michael2);
assertFalse(michael == michael3);
assertTrue(michael.equals(michael2));
assertTrue(michael.equals(michael3));
assertTrue(michael == michael4);
assertTrue(michael.equals(michael4));
}
}
There is nothing fancy about the unit test in Listing 12-1. All it does is prove that using == when
comparing String s isn't the same as using the .equals method. However, let's walk through the different
pieces of the test. First, a JUnit test case a regular POJO. You aren't required to extend any particular
class, and the only requirement that JUnit has for your class is that it have a no argument constructor.
In each test, you have one or more test methods (one in this case). Each test method is required to
be public, to be void, and to take zero arguments. To indicate that a method is a test method to be
executed by JUnit, you use the @Test annotation. JUnit executes each method annotated with the @Test
annotation once during the execution of a given test.
The last piece of StringTest are the assert methods used in the test method. The test method has a
simple flow. It begins by setting up the conditions required for this test, and then it executes the tests
and validates the results at the same time using JUnit's assert methods. The methods of the
org.junit.Assert class are used to validate the results of a given test scenario. In the case of StringTest
in Listing 12-1, you're validating that calling the .equals method on a String object compares the
contents of the string, whereas using == to compare two strings verifies that they're the same instance
only.
Although this test is helpful, there are a couple other useful annotations that you should know about
when using JUnit. The first two are related to the JUnit test lifecycle. JUnit allows you to configure
methods to run before each test method and after each test method so that you can set up generic
preconditions and do basic cleanup after each execution. To execute a method before each test method,
you use the @Before annotation; @After indicates that the method should be executed after each test
method. 2 Just like any test method, the @Before ( setUp ) and @After ( tearDown ) marked methods are
required to be public, be void, and take no arguments. Typically, you create a new instance of an object
to be tested in the method marked with @Before to prevent any residual effects from one test having an
effect on another test. Figure 12-1 shows the lifecycle of a JUnit test case using the @Before , @Test , and
@After annotations.
2 These methods were called setUp and tearDown in previous versions of JUnit.
 
Search WWH ::




Custom Search