JUnit
Learn about JUnit and its features.
We'll cover the following...
What is JUnit?
JUnit is a simple framework to write repeatable tests.
A typical JUnit 4.x test consists of multiple methods annotated with the @Test
annotation.
At the top of every JUnit test class, we should include all the static Assert methods and annotations like so:
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.Before;
import org.junit.After;
Use the @Before
to annotate initialization methods that are run before every test and @After
to
annotate break-down methods that are run after every test.
Each test method should test one thing, and the method name should reflect the test’s purpose. For example:
public void toStringYieldsTheStringRepresentation() {
String[] array = {"a", "b", "c"};
ArrayWrapper<String> arrayWrapper = new ArrayWrapper<String>(array);
assertEquals("[a, b, c]", arrayWrapper.toString());
}
Hamcrest
In more recent versions (JUnit 4.4+), JUnit also includes Hamcrest matchers:
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
Then you can create more readable tests using the Hamcrest core-matchers. For example:
@Test
public void sizeIs10() {
assertThat(wrapper.size(), is(10));
}
Assumptions
Often, there are variables outside of a test that is beyond your control. But the test ...