这是一个单元测试类:
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。参数化单元测试不方便,因为它们会为“value1”和“value2”执行 test1,为“value1”和“value2”执行 test2,这不是我想要的。
我虽然关于:
- 每次进行测试时调用 setup 方法。
使用@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";
}
任何想法 ?