简体   繁体   中英

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);
  }
..
}

If they are completely independent then write independent tests, but if they are closely related (looks like it) then just have a single test with the four calls, each call wrapped in a try-catch, and a fail('exception expected') after each call. As it was done in junit 3.

Rather than creating separate methods just for specifying separate arguments to your method under test. Use JUnit Parameterized Test . Here is an example for Fibonacci series.

So you will be able to use this in your implementation and expect ArrayIndexOutOfBounds for the single test method.

@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));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM