Saturday, 31 August 2013

organising junit tests that expect an exception

organising junit tests that expect an exception

I have a class which internally uses a 2D array ,and exposes a
processItem(int i,int j) method as given below. The method uses 1-based
index and has a constructor which takes an int value (say N) as the 2D
array size. So, for N=10, the value of i and j should be 1 to N .If the
method is called with i or j less than 1 or greater than 10 ,the method
would throw an IndexOutOfBoundsException .
In my unit test ,I want to call the method with i,j values
(0,4),(11,3),(3,0),(3,11)
and these calls should throw IndexOutOfBoundsException
How do I organise the tests, do I have to write 1 separate test for each
i,j pair? Or is there a better way to organise them?
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);
}
..
}

No comments:

Post a Comment