Skip to main content
Jump to: navigation, search

Migrating to PDT test framework based on Junit4

PDT Test Framework Cookbook (delta from Junit3.8)

  1. No need to extend from TestCase - still you can extend from PhpTestCase to have Golden capabilities
  2. use Assertclass for assert<Type> testing
  3. Mark unit test as @GUITest or @HeadlessTest or @BareTest - this annotation indicates which runner to use (GUI, Headless or bare).
  4. Mark test method as @Test
  5. Mark as @Before methods that should be run before each test method
  6. Mark as @After methods that should be run after each test method
  7. Mark as @BeforeClass method that should be run before all test methods
  8. Mark as @AfterClass method that should be run after all test methods
  9. Add parameter (expected=<ExceptionClass.class>) to the @Test annotation
  10. Add parameter (timeout=<ms>) to the @Test annotation
  11. Add @Ignore to ignore the test
  12. Add @Parameter to run unit test several times with different parameters.

Example 1

import org.junit.*;
import junit.framework.JUnit4TestAdapter;
import java.util.Vector;

public class SimpleUnitTest {
	
	String value;
	
	@Before public void setUp() {
		value="start";
	}

	@Test public void testValue() {
		Assert.assertEquals("start", value);
		value += " 1";
		Assert.assertEquals("start 1", value);
	}

	@Ignore public void testDoNothing() {
		Assert.assertTrue(true);
	}

	@Test(expected=ArrayIndexOutOfBoundsException.class)
	public void testException() {
		Vector test = new Vector();
		Assert.assertEquals(0, test.elementAt(42));
	}
	
	@After public void tearDown() {
		value="";
	}

}

Example 2

@RunWith(Parameterized.class)
public class ParametricRegularExpressionTest {

	private String phrase;
 	private boolean match;

	private static String zipRegEx = "^\d{5}([\-]\d{4})?$";
	private static Pattern pattern;

	public ParametricRegularExpressionTest(String phrase, boolean match) {
		super();
		this.phrase = phrase;
		this.match = match;
	}

 	@Parameters
	public static Collection regExValues() {
		return Arrays.asList(new Object[][] {
   			{"22101", true },
   			{"221x1", false },
   			{"22101-5150", true },
   			{"221015150", false }});
 	}

	@Test
	public void verifyGoodZipCode() throws Exception{
		Matcher mtcher = this.pattern.matcher(phrase);
		boolean isValid = mtcher.matches();
		assertEquals("Pattern did not validate zip code", isValid, match);
	}

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		pattern = Pattern.compile(zipRegEx);
	}
}

Back to the top