2013-08-31 1 views
1

내부적으로 2D 배열을 사용하는 클래스가 있으며 아래 주어진대로 processItem (int i, int j) 메서드를 노출합니다. 이 메서드는 1부터 시작하는 인덱스를 사용하고 2D 배열 크기로 int 값 (예 : N)을 사용하는 생성자를가집니다. 따라서 N = 10의 경우 i와 j의 값은 1에서 N이되어야합니다. 메서드가 i 또는 j가 1보다 작거나 10보다 큰 경우 메서드가 호출되면 IndexOutOfBoundsException이 throw됩니다. 제 단위 테스트 예외가 예상되는 junit 테스트 구성

이 난으로 메소드를 호출하려면, j는 (3,11)

, (3,0)을 (11,3)을

(0,4)를 값

이 호출은 IndexOutOfBoundsException을 던져야 함

어떻게 테스트를 구성합니까? 각 i, j 쌍에 대해 각각 별도의 테스트를 작성해야합니까? 아니면 그들을 구성하는 더 좋은 방법이 있습니까?

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

답변

1

은 다음 완전히 독립적 인 경우 독립적 인 테스트를 작성하지만이 밀접하게 관련되어있는 경우 (그 모양) 그럼 그냥 네 통화와 단일 테스트, 시도 - 캐치에 싸여 각 통화를하고, 각 통화 후 fail('exception expected') junit 3에서 그랬던 것처럼.

1

테스트중인 메소드에 대해 별도의 인수를 지정하는 대신 별도의 메소드를 작성하는 것이 아닙니다. JUnit Parameterized Test을 사용하십시오. 다음은 피보나치 시리즈의 예입니다.

구현시이 값을 사용할 수 있으며 단일 테스트 방법으로는 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)); 
    } 
}