Junit

Exceptions

import org.junit.Test;

@Test(expected = ArrayIndexOutOfBoundsException.class)
public void mustThrowArrayIndexOutOfBoundsException() {
    int i = new int[]{1}[2]; // will not compile if you do not have the assignment
}

Hamcrest

JavaDoc

Assertions

Asserting array equality

// core java
new int[]{1, 2, 3}.equals(new int[]{1, 2, 3}); // false

// junit assert
import org.junit.Assert;

Assert.assertEquals(new int[]{1, 2, 3}, (new int[]{1, 2, 3})); // fails

// hamcrest matchers
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;

MatcherAssert.assertThat(new int[]{1, 2, 3}, CoreMatchers.equalTo(new int[]{1, 2, 3})); // passes

Asserting type of an object

MatcherAssert.assertThat("", CoreMatchers.instanceOf(String.class));
MatcherAssert.assertThat((Runnable) () -> {}, CoreMatchers.instanceOf(Runnable.class));

Using the is decorator with static imports

Show off and nothing else

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.*;

assertThat(Boolean.TRUE, is(equalTo(true)));

Examples

Loading a File from Maven Resources Directory in Unit Test

Given the following directory layout..

.
├── pom.xml
└── src
    └── test
        ├── java
        │   └── TestClass.java
        └── resources
            └── sampledata
                └── helloworld.txt

.. here is an example how TestClass can load helloworld.txt

import java.util.List;

import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;

import org.junit.Test;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;

public class TestClass {
    @Test
    public void testLoadFile() throws Exception {
        Path helloworld = Paths.get("src", "test", "resources", "sampledata", "helloworld.txt");
        List<String> lines = Files.readAllLines(helloworld, StandardCharsets.UTF_8);
        MatcherAssert.assertThat(lines.get(0), CoreMatchers.equalTo("Hello World!"));
    }
}