有如下描述一个很好的可能性,运行与其中不同的数据多次执行同样的测试方法参数JUnit测试:http://junit.org/apidocs/org/junit/runners/Parameterized.html使用非原始参数进行参数化的JUnit测试?
不幸的是,它似乎只可以使用原始的参数或字符串,但不是对象。有没有已知的解决方法?
有如下描述一个很好的可能性,运行与其中不同的数据多次执行同样的测试方法参数JUnit测试:http://junit.org/apidocs/org/junit/runners/Parameterized.html使用非原始参数进行参数化的JUnit测试?
不幸的是,它似乎只可以使用原始的参数或字符串,但不是对象。有没有已知的解决方法?
使用@Parameters注释的data()
方法的类型是List<Object[]>
,因此您可以放入任何对象。
要通过在,例如,一个Money
对象,您的阵列被转换为一个列表将是:
{{新钱(26, “CHF”)}, {新钱(12 ,“USD”)}}
测试类的构造函数应该接受一个Money对象作为参数。
最近我开始zohhak项目。它可以让你写:
@TestWith({
"25 USD, 7",
"38 GBP, 2",
"null, 0"
})
public void testMethod(Money money, int anotherParameter) {
...
}
使用对象也可以使用Junit @Parameters
。
例子: -
@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));
}
}
你搞清楚这个问题的任何解决方案? – 2017-10-25 15:04:03