Assertion - org.junit.Assert
- Equals, NotEquals, True, False, Null, NotNull - Arrays, Object & Strings
Test Aggregation
import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ TestFeatureLogin.class, TestFeatureLogout.class, TestFeatureNavigate.class, TestFeatureUpdate.class }) public class FeatureTestSuite { // the class remains empty, // used only as a holder for the above annotations }
Exception Testing
@Test(expected= IndexOutOfBoundsException.class) public void empty() { new ArrayList<Object>().get(0); }
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldTestExceptionMessage() throws IndexOutOfBoundsException {
List
Matchers and assertthat
assertThat(x, is(3));
assertThat(x, is(not(4)));
assertThat(responseString, either(containsString("color")).or(containsString("colour")));
assertThat(myList, hasItem("3"));
Ignoring tests
@Ignore("Test is ignored as a demonstration")
@Test
public void testSane() {
assertThat(1, is(1));
}
Timeout for tests
@Test(timeout=1000) public void testWithTimeout() { ... }
public class HasGlobalTimeout { public static String log; @Rule public Timeout globalTimeout = new Timeout(10000); // 10 seconds max per method tested @Test public void testInfiniteLoop1() { log += "ran1"; for (;;) { } } @Test public void testInfiniteLoop2() { log += "ran2"; for (;;) { } } }
Comments