Junit 3 On One Page: Fixture Object, Shared by

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

JUnit 3 on one page

package info.jbrains.junit3;
import
import
import
import

java.awt.event.ActionListener;
java.util.*;
java.util.regex.Matcher;
java.util.regex.Pattern;

naming convention for test case classes

import junit.framework.TestCase;

fixture object, shared by


multiple tests

this class has tests

public class ComprehensiveExampleTest extends TestCase {


private Matcher matcher;

a test method

protected void setUp() throws Exception {


matcher = Pattern.compile("(\\d\\d)(\\d)").matcher("762");
}

check the expected value


against the computed value

public void testBasicAddition() throws Exception {


assertEquals(7, 2 + 5);
}

check any boolean condition

public void testMatchingRegularExpressions() throws Exception {


assertTrue(Pattern.matches("\\d\\d\\d", "762"));
assertFalse(Pattern.matches("\\d\\d\\d", "No 3 digits in a row"));
}

optional message to help


identify the failure

public void testCapturingMatchedExpressions() throws Exception {


assertTrue(matcher.matches());
assertEquals("group 0", "762", matcher.group(0));
assertEquals("group 1", "76", matcher.group(1));
assertEquals("group 2", "2", matcher.group(2));
}
public void testTryUsingGroupsBeforeInvokingMatches() throws Exception {
try {
naming convention for
matcher.group(2);
fail("How did that work?!");
expected exception
}
catch (IllegalStateException expected) {
}
}

this line should not be reached

public void testFindItemInCollection() throws Exception {


ActionListener actionListener = new DoNothingActionListener();
List list = new ArrayList();

verify the computed result is the


same physical object as the
expected result

step 1: create some objects

assertSame(actionListener, list.get(0));

step 3: check the result

private void testThisIsNotATest() throws Exception {


fail("I generate a warning, because I'm not public");
}
public void testThisIsNotATestEither(String parameter) throws Exception {
fail("JUnit silently ignores me, because I take a parameter");
}
}

unexpected exceptions handled


by JUnit framework

step 2: invoke a method

public void testListCanStoreNullObjects() throws Exception {


List list = Collections.singletonList(null);
assertNotNull(list);
assertNull(list.get(0));
}

methods JUnit won't run as tests

verify the right exception is thrown

list.add(actionListener);

check object references are


null, or not null

invoked before each test (method)


to set up common test data

You might also like