Java Reference
In-Depth Information
To begin, you can create a JUnit test case the same way you create a new class. Eventually, you will
create a test case for a class you've already developed, but practice with a standalone test case first.
You create a new JUnit test case under File New JUnit Test Case or by right‐clicking in the
Navigator and selecting New JUnit Test Case. Name your test case JUnitTest . There are check-
boxes next to several methods; select setUpBeforClass() , setUp() , tearDownAfterClass() , and
tearDown() to create auto stubs. Finally, make sure the “Class Under Test” field is blank, since you
are not testing a class right now. Press Finish to create your test case. You should have a class that
looks like this:
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class JUnitTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
fail("Not yet implemented");
}
}
The text beginning with the @ symbol are called annotations , and these indicate the purpose of specific
methods. You will see more annotations as you move through later chapters in the topic. The difference
between comments and annotations is that annotations can be processed during compilation. Therefore,
you should be careful to use the annotations correctly. There are five annotations you will see in JUnit
tests: @Test , @BeforeClass , @AfterClass , @Before , and @After . The first, @Test , annotates each test
method. There is no universally accepted naming convention for test methods, but it makes sense to
name them in a way that makes it clear what you are testing and under what conditions.
The other four annotations allow you to prepare some objects and resources for use before your tests
begin and to close out things appropriately after your tests are finished. The two setup methods, anno-
tated @BeforeClass and @Before , are used to create necessary objects for testing. The first type, @
BeforeClass , is run once before anything else, and the results will be shared by all the tests. This is
helpful for timely processes like logging into a database. The second type, annotated @Before , runs
Search WWH ::




Custom Search