JUnit Started Guide


I read JUnit4 Official GitHub Wiki:
junit-team/junit4 Official GitHub Wiki


πŸ€ Assertions

public class AssertTests {
@Test
public void testAssertArrayEquals() {
byte[] expected = "trial".getBytes();
byte[] actual = "trial".getBytes();
assertArrayEquals("failure - byte arrays not same", expected, actual);
}

@Test
public void testAssertEquals() {
assertEquals("failure - strings are not equal", "text", "text");
}

@Test
public void testAssertFalse() {
assertFalse("failure - should be false", false);
}

@Test
public void testAssertNotNull() {
assertNotNull("should not be null", new Object());
}

@Test
public void testAssertNotSame() {
assertNotSame("should not be same Object", new Object(), new Object());
}

@Test
public void testAssertNull() {
assertNull("should be null", null);
}

@Test
public void testAssertSame() {
Integer aNumber = Integer.valueOf(768);
assertSame("should be same", aNumber, aNumber);
}

// JUnit Matchers assertThat
@Test
public void testAssertThatBothContainsString() {
assertThat("albumen", both(containsString("a")).and(containsString("b")));
}

@Test
public void testAssertThatHasItems() {
assertThat(Arrays.asList("one", "two", "three"), hasItems("one", "three"));
}

@Test
public void testAssertThatEveryItemContainsString() {
assertThat(Arrays.asList(new String[] { "fun", "ban", "net" }), everyItem(containsString("n")));
}

// Core Hamcrest Matchers with assertThat
@Test
public void testAssertThatHamcrestCoreMatchers() {
assertThat("good", allOf(equalTo("good"), startsWith("good")));
assertThat("good", not(allOf(equalTo("bad"), equalTo("good"))));
assertThat("good", anyOf(equalTo("bad"), equalTo("good")));
assertThat(7, not(CombinableMatcher. either(equalTo(3)).or(equalTo(4))));
assertThat(new Object(), not(sameInstance(new Object())));
}

@Test
public void testAssertTrue() {
assertTrue("failure - should be true", true);
}
}

Readable failure messages. Compare:

assertTrue(responseString.contains("color") || responseString.contains("colour"));
// ==> failure message:
// java.lang.AssertionError:

assertThat(responseString, anyOf(containsString("color"), containsString("colour")));
// ==> failure message:
// java.lang.AssertionError:
// Expected: (a string containing "color" or a string containing "colour")
// got: "Please choose a font"

πŸ—½ Exception testing

The @Test annotation has an optional parameter β€œexpected” that takes as values subclasses of Throwable.

@Test(expected = IndexOutOfBoundsException.class) 
public void empty() {
new ArrayList().get(0);
}

More detail is as follows: hamcrest - Tutorial.wiki

πŸ—» Ignore

Note that @Ignore takes an optional parameter (a String)
if you want to record a reason why a test is being ignored.

@Test
@Ignore
public void Sample() {
assertTrue(false);
}

πŸ‘½ Assumptions

The default JUnit runner treats tests with failing assumptions as ignored.

import static org.junit.Assume.*
@Test public void filenameIncludesUsername() {
assumeThat(File.separatorChar, is('/'));
assertThat(new User("optimus").configFileName(), is("configfiles/optimus.cfg"));
}

@Test public void correctBehaviorWhenFilenameIsNull() {
assumeTrue(bugFixed("13356")); // bugFixed is not included in JUnit
assertThat(parse(null), is(new NullDocument()));
}

A failing assumption in a @Before or @BeforeClass method will have the same effect
as a failing assumption in each @Test method of the class.

πŸ˜€ Rules

Rules allow very flexible addition or redefinition of the behavior of each test method in a test class.

TemporaryFolder Rules

The TemporaryFolder Rule allows creation of files and folders that are deleted when the test method finishes

public static class HasTempFolder {
@Rule
public TemporaryFolder folder = new TemporaryFolder();

@Test
public void testUsingTempFolder() throws IOException {
File createdFile = folder.newFile("myfile.txt");
File createdFolder = folder.newFolder("subfolder");
// ...
}
}

ExternalResource Rules

ExternalResource is a base class for Rules (like TemporaryFolder) that set up
an external resource before a test, and guarantee to tear it down afterward:

public static class UsesExternalResource {
Server myServer = new Server();

@Rule
public ExternalResource resource = new ExternalResource() {
@Override
protected void before() throws Throwable {
myServer.connect();
};

@Override
protected void after() {
myServer.disconnect();
};
};

@Test
public void testFoo() {
new Client().run(myServer);
}
}

ErrorCollector Rules

The ErrorCollector Rule allows execution of a test to continue afte the first problem is found:

public static class UsesErrorCollectorTwice {
@Rule
public ErrorCollector collector = new ErrorCollector();

@Test
public void example() {
collector.addError(new Throwable("first thing went wrong"));
collector.addError(new Throwable("second thing went wrong"));
}
}

ExceptedException RUles

The ExpectedException RUle allows in-test specification of expected exception types and messages:

public static class HasExpectedException {
@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void throwsNothing() {

}

@Test
public void throwsNullPointerException() {
thrown.expect(NullPointerException.class);
throw new NullPointerException();
}

@Test
public void throwsNullPointerExceptionWithMessage() {
thrown.expect(NullPointerException.class);
thrown.expectMessage("happened?");
thrown.expectMessage(startsWith("What"));
throw new NullPointerException("What happened?");
}
}

🐯 Test fixtures

A test fixture is a fixed state of a set of objects used as a baseline for running tests.

An example of usage:

package test;

import java.io.Closeable;
import java.io.IOException;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestFixturesExample {
static class ExpensiveManagedResource implements Closeable {
@Override
public void close() throws IOException {}
}

static class ManagedResource implements Closeable {
@Override
public void close() throws IOException {}
}

@BeforeClass
public static void setUpClass() {
System.out.println("@BeforeClass setUpClass");
myExpensiveManagedResource = new ExpensiveManagedResource();
}

@AfterClass
public static void tearDownClass() throws IOException {
System.out.println("@AfterClass tearDownClass");
myExpensiveManagedResource.close();
myExpensiveManagedResource = null;
}

private ManagedResource myManagedResource;
private static ExpensiveManagedResource myExpensiveManagedResource;

private void println(String string) {
System.out.println(string);
}

@Before
public void setUp() {
this.println("@Before setUp");
this.myManagedResource = new ManagedResource();
}

@After
public void tearDown() throws IOException {
this.println("@After tearDown");
this.myManagedResource.close();
this.myManagedResource = null;
}

@Test
public void test1() {
this.println("@Test test1()");
}

@Test
public void test2() {
this.println("@Test test2()");
}
}

Will Output something like the following:

@BeforeClass setUpClass
@Before setUp
@Test test2()
@After tearDown
@Before setUp
@Test test1()
@After tearDown
@AfterClass tearDownClass

πŸ–₯ Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!