jam*_*jam 10 java junit exception
让我们假设一个简单的方法,它抛出一IndexOutOfBoundsException
对无效的索引(2d数组).
我如何测试,所有坏指数组合都会引发异常?
(当然,如果一个电话抛出异常,这个测试将不会继续)
@Test(expected = Exception.class)
public void validateIndices(){
check(0,-1);
check(-1,0);
check(0,COLS + 1);
check(ROWS + 1, 0);
}
Run Code Online (Sandbox Code Playgroud)
是否有一种常用的方法来测试方法的参数变化?
除了@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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
每个理论都将检查与理论假设相匹配的行和列的所有可能组合.
或者,如果您的列和行列表相同,则可以更轻松地完成:
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
在你的情况,我想Parameterized我的单元测试,测试使用相同的测试更多信息所有组合在这里.
在你的情况下,它看起来像这样:
@RunWith(Parameterized.class)
public class MyTest {
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ 0, -1 }, { -1, 0 }
});
}
@Parameterized.Parameter
public int row;
@Parameterized.Parameter(value = 1)
public int col;
@Test(expected = IndexOutOfBoundsException.class)
public void validateIndices(){
check(row, col);
}
}
Run Code Online (Sandbox Code Playgroud)