datka
datka

Reputation: 880

Parameterized JUnit tests with non-primitive parameters?

There is a nice possibility to run JUnit test with parameters where the same test method is executed multiple times with different data as described here: http://junit.org/apidocs/org/junit/runners/Parameterized.html

Unfortunately, it only seems possible to use primitive parameters or Strings, but not objects. Is there any workaround known for this?

Upvotes: 7

Views: 9863

Answers (3)

Shantonu
Shantonu

Reputation: 1301

Using object is also possible using Junit @Parameters.

Example:-

@RunWith(Parameterized.class)
public class TestParameter {

@Parameter(value=0)
public int expected;

@Parameter(value=1)
public int first;

@Parameter(value=2)
public int second;
private Calculator myCalculator;


@Parameters(name = "Test : {index} : add({1}+{2})= Expecting {0}")//name will be shared among all tests
public static Collection addNumbers() {
    return Arrays.asList(new Integer[][] { { 3, 2, 1 }, { 5, 2, 3 }, { 9, 8, 1 }, { 200, 50, 150 } });
}
@Test
public void testAddWithParameters() {
    myCalculator = new Calculator();
    System.out.println(first + " & " + second + " Expected = " + expected);
    assertEquals(expected, myCalculator.Add(first, second));
}

}

Upvotes: 0

piotrek
piotrek

Reputation: 14520

recently i started zohhak project. it lets you write:

@TestWith({
   "25 USD, 7",
   "38 GBP, 2",
   "null,   0"
})
public void testMethod(Money money, int anotherParameter) {
   ...
}

Upvotes: 1

avandeursen
avandeursen

Reputation: 8648

The type of the data() method in the use of the @Parameters annotation is List<Object[]>, so you can put in any object.

To pass in, e.g., a Money object, your array to be converted to a list would be:

{ { new Money(26, "CHF") }, { new Money(12, "USD") } }

The constructor of the test class should take a Money object as argument then.

Upvotes: 9

Related Questions