Parameterized JUnit tests with non-primitive parameters?
Asked Answered
K

3

7

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?

Kaine answered 9/2, 2012 at 17:2 Comment(1)
Did you figure out any solution for this problem?Fainthearted
E
9

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.

Eldenelder answered 9/2, 2012 at 18:51 Comment(0)
P
1

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) {
   ...
}
Pelag answered 5/12, 2012 at 15:45 Comment(0)
I
0

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));
}

}

Imminent answered 1/2, 2016 at 6:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.