Skip to main content

Run, JUnit! Run!!!

This blog post is crossposted and originally part of the 2013 edition Java Advent Calendar a lovely initiative from Attila-Mihaly Balazs and the Transilvania JUG 

JUnit together with JavaScript and SVN are some of the technologies that programmers often start using without even reading a single blog post let alone a book.  Maybe this is a good thing since they look simple enough and understandable so we can use them right away without any manuals, but this also means that they are also underused. In this article we will go through some features of JUnit that I consider very useful.

Parameterized tests 

Sometimes we need to run the same method or functionality with many different inputs and different expected results. One way to do this would be to create separate tests for each of the cases, or you
can use loop but that it would be harder to track down the origin of a possible test failure.

For example if we have the following value object representing rational numbers:

public class RationalNumber {

  private final long numerator;
  private final long denominator;

  public RationalNumber(long numerator, long denominator) {
    this.numerator = numerator;
    this.denominator = denominator;

  public long getNumerator() {
    return numerator;

  public long getDenominator() {
    return denominator;

  public String toString() {
    return String.format("%d/%d", numerator, denominator);
And we have a service class called App with a method convert that divides the number to a rounded value of 5 decimal :

public class App {

   * THE Logic
   * @param number some rational number
   * @return BigDecimal rounded to 5 decimal points
  public static BigDecimal convert(RationalNumber number) {
    BigDecimal numerator = new BigDecimal(number.getNumerator()).
        setScale(5, RoundingMode.HALF_UP);

    BigDecimal result = numerator.divide(
        new BigDecimal(number.getDenominator()),

    return result;

And for the actual AppTest class we have

public class AppTest {

  private RationalNumber input;
  private BigDecimal expected;

  public AppTest(RationalNumber input, BigDecimal expected) {
    this.input = input;
    this.expected = expected;

  @Parameterized.Parameters(name = "{index}: number[{0}]= {1}")
  public static Collection<Object> data() {
    return Arrays.asList(new Object[][]{
      {new RationalNumber(1, 2), new BigDecimal("0.50000")},
      {new RationalNumber(1, 1), new BigDecimal("1.00000")},
      {new RationalNumber(1, 3), new BigDecimal("0.33333")},
      {new RationalNumber(1, 5), new BigDecimal("0.20000")},
      {new RationalNumber(10000, 3), new BigDecimal("3333.33333")}

  public void testApp() {
    //given the test data
    BigDecimal out = App.convert(input);
    Assert.assertThat(out, is(equalTo(expected)));


The Parametrized runner or  @RunWith(Parameterized.class)  enables the "parametrization" or in other words the injection of the collection of values annotated with  @Parameterized.Parameters into the Test constructor where each of the sublist is an parameter list.  This means that each of the RationalNumber objects in the data() method will be injected into the input variable and each of the BigDecimal values would be the expected value, so in our example we have 5 tests.

There is also an optional custom naming of the generated test added in the annotation, so "{index}: number[{0}]= {1}" will be replaced with the appropriate parameters defined in the data() method and the "{index}" placeholder will be the test case index, like in the following image

Running the parametrized tests in IntelliJ Idea 

JUnit rules

The simplest definition of JUnit rules is that they are in a sense an interceptors  and very similar to the Spring aspect oriented programming or Java EE interceptors API. Basically you can do useful things before and after the test execution.
OK so let's start with some of the built in test rules. One of them is ExternalResource  where the idea is that we setup an external resource and after the teardown garteet the resource was freed up. A classic example of such test is a creation of file, so for that purpose we have a built in class TemporaryFolder but we can also create our own ones for other resources :

  public class TheRuleTest {
  public TemporaryFolder folder = new TemporaryFolder();

  public void someTest() throws IOException {
    final File tempFile = folder.newFile("thefile.txt");
    tempFile.setExecutable(true)  ;
    assertThat(tempFile.canExecute(), is(true));

We could have done this in a @Before and @After blocks and use java temp files but it is easy to forget something and leave some of the files unclosed in some of the scenarios where a test fails.

For example there is also a Timeout rule for methods where if the the execution is not finished in given time limit the test will fail with a Timeout exception. For example to limit the running for 20 milliseconds :

public MethodRule globalTimeout = new Timeout(20);

We can implement our own rules that can do a policy enforcement or various project specific changes. The only thing that needs to be done is for us to implement the TestRule interface.
A simple scenario to explain the behaviour is to add a rule that prints someting before and after test.

import org.junit.rules.TestRule;

import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class MyTestRule implements TestRule {

  public class MyStatement extends Statement {

    private final Statement statement;

    public MyStatement(Statement statement) {
      this.statement = statement;

    public void evaluate() throws Throwable {
      System.out.println("before statement" );
      System.out.println("after statement");


  public Statement apply(Statement statement,
                         Description description) {

    System.out.println("apply rule");
    return new MyStatement(statement);


So now that we have our rule we can use it in tests, were the tests will just print out different values:

public class SomeTest {

  public MyTestRule folder = new MyTestRule();

  public void testA()  {

  public void testB()  {
When we run a test the following output will be created on the  console output :

apply rule
before statement
after statement
apply rule
before statement
after statement
From the built in one there is one called ExpectedException that can very useful when trying out testing errors. Additionally there is an option to chain the rules that can be useful in many scenarios.

To sum up

If you wanna say that Spock or TestNG or some library build on top of JUnit have more features than JUnit, than that is probably true.
But you know what? We don't always have those on our class path and chances are that JUnit is there and already used all over the place. Than why not use it's full potential ?

Useful links

Popular posts from this blog

HTML 5 data-* attributes, how to use them and why

It is always tempting to add custom attributes in HTML so that you can use the data stored there to do X. But if you do that there is no way of knowing if your HTML attribute will not be overridden in the future and used for something else and additionally you will not be writing valid HTML markup that can pass HTML 5 validator and with that you can create some very bad side effects. That is why there is a spec in HTML 5 called custom data attributes that enable number of useful features.

You may go around and read the specs, but the basic idea is very simple, you can add any attribute that starts with "data-" and that attribute will be treated as non-visible data for that attribute. By non-visible I mean that it is not something that gets rendered to the client so it does not affect the layout or style of the page, but it is there in the HTML so in no way this is private.
So let's get right into it, the following snippet is a valid HTML5 markup

<div id="aweso…

Basic Authentication with RestTemplate

Spring Rest Templates are very good way of writing REST clients. By default they work with basic HTTP so if we need to use Basic Authorization we would need to init the rest template with custom HttpClient. This way the Rest Template will automatically use Basic Auth and append to the HTTP headers "Authorization: Basic BASE64ENCODED_USER_PASS".

HttpClient client = new HttpClient(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("USERNAME","PASS"); client.getState().setCredentials( new AuthScope("", 9090, AuthScope.ANY_REALM), credentials); CommonsClientHttpRequestFactory commons = new CommonsClientHttpRequestFactory(client); RestTemplate template = new RestTemplate(commons); SomeObject result = template.getForObject( "",SomeObject.class );

In EE application this would probably be managed by DI framework like Spring Core and only initialized once sin…

Temporary files and directories in Java 7 and before

Sometimes we want to create a temporary file, whether to save some data that gets written by some other application or just to temporary store stuff. Well, usually applications have their own temporary folder where they do this and it gets somehow configured. But why not use the underlying OS specific file like "/tmp/" in Linux so there must be some system property that has this info and there is. The key is "" resulting in "/tmp" in my case or by code:
String tempDir = System.getProperty(""); We can use tempDir  folder as a temporary place to store files, but there are a lot nicer ways to work with files like this even in JDK6 not just in JDK7:
import; import; import java.nio.file.Files; import java.nio.file.Path; public class TempFile { public static void main(String[] args) { try { // create a temp file File tempFile = File.createTempFile("old-file",…