这是一个单元测试类:
MyUnitTestSetup myUnitTestSetup ;
public void setUp(String myParam){
myUnitTestSetup = new MyUnitTestSetup(myParam);
}
@Test
public void test1(){
setUp("value1");
//do some stuff with myParam = "value1";
}
@Test
public void test2(){
setUp("value2");
//do some stuff with myParam = "value2";
}
我想用“value1”执行test1,用“value2”执行test2。参数化单元测试不方便,因为它们将执行test1为“value1”和“value2”,test2为“value1”和“value2执行不是我想要的。”
我虽然关于:
使用@Rule注释:
static String myParam;
MyUnitTestSetup myUnitTestSetup ;
@Before
public void setUp(){
myUnitTestSetup = new MyUnitTestSetup(myParam);
}
@Rule
public TestRule rule = new TestRule() {
@Override
public Statement apply(final Statement base, final Description desc) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
if(desc.getMethodName().equals("test1"))
myParam = "value1";
...
}
};
}
}
@Test
public void test1(){
//do some stuff with myParam = "value1";
}
@Test
public void test2(){
//do some stuff with myParam = "value2";
}
但我想知道是否有更干净的&更聪明的方式。我会想到这样的事情:
MyUnitTestSetup myUnitTestSetup ;
@Before
public void setUp(String myParam){
myUnitTestSetup = new MyUnitTestSetup(myParam);
}
@Test(myParam="value1")
public void test1(){
//do some stuff with myParam = "value1";
}
@Test(myParam="value2")
public void test2(){
//do some stuff with myParam = "value2";
}
有什么想法吗?
答案 0 :(得分:3)
我在这里遗漏了什么吗?为什么不将它设置为测试调用中的第一个东西或调用设置的方法。
@Test
public void test1(){
myParam = "value1"; //set the value?
...
}
@Test
public void test2(){
setupMyParam("value2"); // or this?
...
}
答案 1 :(得分:0)
不确定使用TestNG是否适合您,但如果可以,TestNG允许您1)将参数直接传递给测试方法,2)根据您的需要为每个类定义数据提供者。例如:
@DataProvider
public Object[][] dp1() {
return new Object[][] {
new Object[] { "value1"};
}
}
@Test(dataProvider = "dp1")
public void test1(String value) {
// will receive "value1"
}
@DataProvider
public Object[][] dp2() {
return new Object[][] {
new Object[] { "value2"};
}
}
@Test(dataProvider = "dp2")
public void test2(String value) {
// will receive "value2"
}
答案 2 :(得分:0)
查看JUnitParams库。有了它,你可以做到:
@Test
@Parameters({ new MyUnitTestSetup("value1") })
public void test1(MyUnitTestSetup myUnitTestSetup1) {
// do some stuff with myUnitTestSetup1
}
@Test
@Parameters({ new MyUnitTestSetup("value2") })
public void test2(MyUnitTestSetup myUnitTestSetup2) {
// do some stuff with myUnitTestSetup2
}