Find out the java testing libraries that will make your life easier


22 August 2014, by

Unit testing is generally considered a good thing, but a worker is only as good as their tools. The tools that immediately spring to mind when writing java unit tests are JUnit, and HamCrest. But are these the best tools for the job? This post explores a couple of alternatives. Depending on the task you are trying achieve, these may be better or worse alternatives, but it’s always good to know your options.

JarSpec

This library is a neat way of writing more descriptive unit tests. It was created by Softwire’s Harry Cummings as a solution which enables Java unit tests to be coded in a manner similar to RSpec:

@RunWith(JarSpecJUnitRunner.class)
public class MinimalSpec implements Specification {
  @Override
  public SpecificationNode root() {
    return describe("addition", () ->
      describe("of 1+1", () -> {
        int result = 1 + 1;
        return by(
          it("should equal 2", () -> assertEquals(2, result)),
          it("should equal 3", () -> assertEquals(3, result))
        );
      })
    );
  }
}

The code to JarSpec is on GitHub.

AssertJ

AssertJ is a matcher library that is set up to allow good integration with IDEs.
Rather than typing:

assertContains(list, value)

which could match several different types other that List, you type:

assertThat(list).contains(value)

Not only is this nicer to read, after typing the period, your IDE can immediately suggest all of the assertions that can be performed on the list. When trying to do code completion in the first example, you have to pick your method from all of the assertions that exist.

The code to AssertJ is on GitHub.

Tags: , , , ,

Categories: Technical

«
»

Leave a Reply

* Mandatory fields


× 5 = forty five

Submit Comment