除了@Nicolas_Filotto 回答,还可以使用Junit Theories。它更具可读性,并且与 Parameterized 不同,它将使用所有可能的参数组合执行测试。
@RunWith(Theories.class)
public class MyTest {
@DataPoints("cols")
public static int[] rowValues(){
return new int[]{0, -1, 1, 2};
}
@DataPoints("rows")
public static int[] colValues(){
return new int[]{0, -1, 4, 5};
}
@Theory
public void upperBoundIsChecked(@FromDataPoints("cols") int col,
@FromDataPoints("rows") int row){
assumeTrue(row >= ROWS || col >= COLS);
try {
check(col, row);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException ignore){}
}
@Theory
public void lowerBoundIsChecked(@FromDataPoints("cols") int col,
@FromDataPoints("rows") int row){
assumeTrue(row < 0 || col < 0);
try {
check(col, row);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException ignore){}
}
@Theory
public void validIndicesNoException(@FromDataPoints("cols") int col,
@FromDataPoints("rows") int row){
assumeTrue(row >= 0 && col >= 0 && row < ROWS && col < COLS);
try {
check(col, row);
} catch (Exception e){
fail("Should not have thrown an exception: " + e.getMessage());
}
}
}
每个理论都会检查与理论假设相匹配的行和列的所有可能组合。
或者,如果您的列和行列表相同,则可以更轻松地完成:
@RunWith(Theories.class)
public class MyTest {
@DataPoints
public static int[] values(){
return new int[]{0, -1};
}
@Theory
public void validateIndices(int col, int row){
check(col,row);
}
}