你看过 JUnit 中的参数化测试吗?这是一个例子:
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class ParamTest {
@Parameters(name = "{index}: fib({0})={1}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] {
{ 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 }
});
}
private int input;
private int expected;
public ParamTest(int input, int expected) {
this.input = input;
this.expected = expected;
}
@Test
public void test() {
Assert.assertEquals(expected, input);
}
}
如果您只想一次运行一个测试,您可以使用私有变量,如下所示:
public class MultipleTest {
private int x;
private int y;
public void test1(){
Assert.assertEquals(x, y);
}
public void test2(){
Assert.assertTrue(x >y);
}
public void args1(){
x=10; y=1;
}
public void args2(){
x=1;y=1;
}
public void args3(){
x=1;y=10;
}
@Test
public void testArgs11(){
args1();
test1();
}
@Test
public void testArgs21(){
args2();
test1();
}
@Test
public void testArgs31(){
args3();
test1();
}
@Test
public void testArgs12(){
args1();
test2();
}
@Test
public void testArgs22(){
args2();
test2();
}
@Test
public void testArgs32(){
args3();
test2();
}
}