Previous Topic: Ant and JUnit Usage ExamplesNext Topic: Integration with CruiseControl


JUnit Usage Examples

JUnit3 Test Cases

JUnit3 Test Suites

JUnit4 Test Cases

JUnit4 Test Suites

 

JUnit3 Test Cases

For JUnit3 test cases, follow the JUnit conventions for writing your test case. In particular:

For example:

import junit.framework.TestCase;
 
public class JUnit3TestCase extends TestCase {
 
   public void testOneIsOne() {
      assertEquals (1, 1);
   }
 
   public void testTwoIsThree() {
      assertEquals (2, 3);
   }
 
}
JUnit3 Test Suites

For JUnit3 test suites, your suite is not required to extend the junit.framework.TestSuite. However, it must implement the suite() method, with test cases wrapped by the JUnit4TestAdapter.

For example:

import junit.framework.Junit4TestAdapter;
import junit.framework.TestSuite;
 
public class JUnit3VanillaTestSuite {
 
   public static TestSuite suite() {
      TestSuite suite = new TestSuite(); 
      suite.addTest ( new JUnit4TestAdapter ( MyJUnit3TestCase.class) ) ;
      return suite;
   }
 
}
JUnit 4 Test Cases

For JUnit4 test cases, the test methods must have the "@org.junit.Test" annotation on the methods, as required by JUnit4.

For example:

import static org.junit.Assert.assertEquals;
 
import org.junit.Test;
 
public class JUnit4TestCase {
 
    @Test
    public void oneIsOne() { assertEquals (1, 1); }
 
    @Test
    public void twoIsThree() { assertEquals (2, 3); }
 
}
JUnit4 Test Suites

To implement a JUnit4 test suite, add the @RunWith and @Suite.SuiteClasses annotations to flag the class as a test suite.

For example:

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
 
@RunWith(Suite.class)
 
@Suite.SuiteClasses ( { JUnit4TestCase.class } )
 
public class JUnit4VanillaTestSuite { // empty }

Note: If loading your JUnit test returns an IllegalArgumentException on the JUnit step, confirm that you added .class to the end of the class name. You can manually verify the spelling of the classname or use the classpath browser to locate the class.