JUnit 4学習ノート(二):パラメータ化テストと仮定(Asumption)


一、簡単なテスト
計算のみを作成する計算機:
 
public class Calculator {
    public static double divide(int dividend, int divisor) {
        return dividend / divisor;
    }
}
 この方法のためにテストを作成します。
 
public class CalculatorTest {
    //    
    private static final double DELTA = 0.01;

    @Test
    public void testAdd() throws Exception {
        assertEquals(3, Calculator.divide(9, 3), DELTA);
    }
}
 このテストでは9割を使って3で方法をテストしましたが、複数のデータを使ってテストしたいです。複数の方法を編纂する必要がないので、JUnitのパラメータ化テストを利用してもいいです。
 
二、パラメータ化テスト
JUnitでは、パラメータテストには2つの形態があり、第1の形態は構造関数形式、すなわちJUnitエルゴードで提供されるすべてのパラメータが構造関数を呼び出し、テスト方法を実行する。
//  Parameterized Runner       
@RunWith(Parameterized.class)
public class CalculatorTest {
    //    
    private static final double DELTA = 0.01;

    private int dividend;
    private int divisor;
    private int result;

    public CalculatorTest(int dividend, int divisor, int result) {
        this.dividend = dividend;
        this.divisor = divisor;
        this.result = result;
    }

    //  @Parameterized.Parameters              ,         
    //       Iterable  ,     public,static,      ,     
    //     (  )           。
    @Parameterized.Parameters
    public static Iterable<Object[]> getParameters() {
        return Arrays.asList(new Object[][]{
                {9, 3, 3}, {5, 1, 5}, {12, 4, 3}
        });
    }

    //      ,      3 
    @Test
    public void testDevide throws Exception {
        assertEquals(result, Calculator.divide(dividend, divisor), DELTA);
    }
}
 
第二は変数注入形態であり、変数の値は構造関数によって初期化されず、JUnitによって注入される。
 
//  Parameterized Runner       
@RunWith(Parameterized.class)
public class CalculatorTest {
    //    
    private static final double DELTA = 0.01;

    //  @Parameter  public  ,JUnit           
    //                      
    @Parameter(0)
    public int dividend;
    @Parameter(1)
    public int divisor;
    @Parameter(2)
    public int result;

    //  @Parameterized.Parameters              ,         
    //       Iterable  ,     public,static,      ,     
    //     (  )           。
    @Parameterized.Parameters
    public static Iterable<Object[]> getParameters() {
        return Arrays.asList(new Object[][]{
                {9, 3, 3}, {5, 1, 5}, {12, 4, 3}
        });
    }

    //      ,      3 
    @Test
    public void testDivide() throws Exception {
        assertEquals(result, Calculator.divide(dividend, divisor), DELTA);
    }
}
 
 
三、アスピリン
上記のパラメータ化の例では、私たちが提供するパラメータが{9,3,3}であれば、 {15,0,0}、{12,4,3}では、第二グループのパラメータはテストに失敗します(15を0で割ると、異常が出ます)が、パラメータ化テストでは0を除数としてテストするべきではないので、テストデータの問題です。テストに失敗するべきではありません。org.junnit.Aspsumeを使用して、テストのデータや環境を仮定することができます。このような仮定が満たされていない場合、このテストをスキップすると、正しいテスト環境でテストが実行されることが保証されます。
 
@Test
public void testDivide() throws Exception {
    //      0,  0     
    assumeTrue("Divisor can't be 0", divisor != 0);
    assertEquals(result, Calculator.divide(dividend, divisor), DELTA);
}
 上記のパラメータを使ってこのテストを実行すると、第二グループのパラメータに対応するテストは失敗ではなく無視されます。