Passing non primitive objects as parameters to a unit test

Filed under: Java, TDD, Test automation, — Tags: JUnit, JUnitParams — Thomas Sundberg — 2014-04-24

How can you pass a parameter to a unit test parametrised with JUnitParams? The answer is simple: As any other parameter.

Create an array with the parameters you want to supply to a test initiated. Make sure that the test method is provided with the parameters. Execute the test class with the right test runner. Done.

An example may look like this:

package se.thinkcode;

import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Test;
import org.junit.runner.RunWith;

import static junitparams.JUnitParamsRunner.$;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;

@RunWith(JUnitParamsRunner.class)
public class NonPrimitiveObjectsTest {

    @Test
    @Parameters(method = "parametersForTestMethod")
    public void shouldReceiveNonPrimitiveParameters(String sample, MyObj myobj) {
        assertFalse("The sample string should not be empty", sample.isEmpty());
        assertNotNull("The non primitive parameter should not be null", myobj);
    }

    @SuppressWarnings("unused")
    private Object[] parametersForTestMethod() {
        return $($("testString", new MyObj()));
    }

    class MyObj {
    }
}

The first thing we notice is the test runner JUnitParamsRunner that will be used to execute the test class, @RunWith(JUnitParamsRunner.class)

The test method is annotated with Parameters and a method that will initiate the parameters is specified. @Parameters(method = "parametersForTestMethod")

The method that creates the parameter array returns an object matrix with the parameters that should be provided to the test method.

Most IDEs will not recognise that this method is used since the only reference to it is in a string. It may therefore be a good idea to annotate it with @SuppressWarnings("unused")
It is being used, but it may be annoying to get warning about an unused method.

The authors of JUnitParams has added some syntactic sugar when creating object arrays and defined $. Looking at the source code reveals that this is just syntactic sugar for

public static Object[] $(Object... params) {
    return params;
}

Resources



(less...)

Pages

About
Events
Why

Categories

Agile
Automation
BDD
Clean code
Continuous delivery
Continuous deployment
Continuous integration
Cucumber
Culture
Design
Executable specification
Gradle
Guice
J2EE
JUnit
Java
Linux
Load testing
Maven
Mockito
Pair programming
PicoContainer
Programming
Public speaking
Quality
Recruiting
Requirements
Scala
Selenium
Software craftsmanship
Software development
Spring
TDD
Teaching
Technical debt
Test automation
Tools
Web
Windows
eXtreme Programming

Authors

Thomas Sundberg
Adrian Bolboaca

Archives

Meta

rss RSS