[英]organising junit tests that expect an exception
我有一個內部使用2D數組的類,並提供下面給出的processItem(int i,int j)方法。 該方法使用基於1的索引,並具有一個構造函數,該構造函數將int值(例如N)作為2D數組大小。 因此,對於N = 10,i和j的值應為1到N。如果在i或j小於1或大於10的情況下調用該方法,則該方法將拋出IndexOutOfBoundsException。
在我的單元測試中,我想用i,j值調用該方法
(0,4),(11,3),(3,0),(3,11)
這些調用應該拋出IndexOutOfBoundsException
如何組織測試,是否必須為每個i,j對編寫1個單獨的測試? 還是有更好的組織方式?
class MyTest{
MyTestObj testobj;
public MyTest(){
testobj = new MyTestObj(10);
}
@Test(expected=IndexOutOfBoundsException.class)
public void test1(){
testobj.processItem(0,4);
}
@Test(expected=IndexOutOfBoundsException.class)
public void test2(){
testobj.processItem(11,3);
}
@Test(expected=IndexOutOfBoundsException.class)
public void test3(){
testobj.processItem(3,0);
}
@Test(expected=IndexOutOfBoundsException.class)
public void test4(){
testobj.processItem(3,11);
}
..
}
如果它們是完全獨立的,則編寫獨立的測試,但是如果它們密切相關(看起來像這樣),則只需對四個調用進行單個測試,每個調用都封裝在try-catch中,並且fail('exception expected')
每次通話后。 就像在junit 3中所做的一樣。
與其創建單獨的方法,而不僅僅是為被測方法指定單獨的參數。 使用JUnit參數化測試 。 這是斐波那契數列的示例。
因此,您將能夠在實現中使用它,並期望將ArrayIndexOutOfBounds
用於單個測試方法。
@RunWith(Parameterized.class)
public class FibonacciTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
Fibonacci,
{ { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 },
{ 6, 8 } } });
}
private int fInput;
private int fExpected;
public FibonacciTest(int input, int expected) {
fInput= input;
fExpected= expected;
}
@Test
public void test() {
assertEquals(fExpected, Fibonacci.compute(fInput));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.