Parameterized JUnit tests with non-primitive parameters?

99封情书 提交于 2019-12-10 14:56:10

问题


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?


回答1:


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.




回答2:


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) {
   ...
}



回答3:


Use JUnitParams instead... junitparams.googlecode.com




回答4:


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

}



来源:https://stackoverflow.com/questions/9215304/parameterized-junit-tests-with-non-primitive-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!