Parameterized JUnit tests with non-primitive param

2019-06-22 12:12发布

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?

4条回答
Root(大扎)
2楼-- · 2019-06-22 12:50

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.

查看更多
仙女界的扛把子
3楼-- · 2019-06-22 13:05

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) {
   ...
}
查看更多
三岁会撩人
4楼-- · 2019-06-22 13:12

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

}

查看更多
SAY GOODBYE
5楼-- · 2019-06-22 13:16

Use JUnitParams instead... junitparams.googlecode.com

查看更多
登录 后发表回答