Thomas Sundberg

April 24, 2014

Passing non primitive objects as parameters to a unit test

Filed under: Java, Programming, TDD — Tags: , , — Thomas Sundberg @ 20:40

This post has been migrated to http: //

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 class.

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;


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at

%d bloggers like this: