もう 1 つの純粋な JUnit でありながら洗練された解決策は、パラメーター化された各テストを独自の内部静的クラスにカプセル化し、最上位のテスト クラスでEnclosedテスト ランナーを使用することです。これにより、テストごとに異なるパラメーター値を互いに独立して使用できるだけでなく、完全に異なるパラメーターを使用してメソッドをテストすることもできます。
これは次のようになります。
@RunWith(Enclosed.class)
public class CalculatorTest {
@RunWith(Parameterized.class)
public static class AddTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ 23.0, 5.0, 28.0 }
});
}
private Double a, b, expected;
public AddTest(Double a, Double b, Double expected) {
this.a = a;
this.b = b;
this.expected = expected;
}
@Test
public void testAdd() {
assertEquals(expected, Calculator.add(a, b));
}
}
@RunWith(Parameterized.class)
public static class SubstractTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ 3.0, 2.0, 1.0 }
});
}
@Parameter(0)
private Double a;
@Parameter(1)
private Double b;
@Parameter(2)
private Double expected;
@Test
public void testSubstract() {
assertEquals(expected, Calculator.substract(a, b));
}
}
@RunWith(Parameterized.class)
public static class MethodWithOtherParametersTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ 3.0, 2.0, "OTHER", 1.0 }
});
}
private Double a;
private BigDecimal b;
private String other;
private Double expected;
public MethodWithOtherParametersTest(Double a, BigDecimal b, String other, Double expected) {
this.a = a;
this.b = b;
this.other = other;
this.expected = expected;
}
@Test
public void testMethodWithOtherParametersTest() {
assertEquals(expected, Calculator.methodWithOtherParametersTest(a, b, other));
}
}
public static class OtherNonParameterizedTests {
// here you can add any other test which is not parameterized
@Test
public void otherTest() {
// test something else
}
}
}
@Parameter
での注釈の使用法に注意してくださいSubstractTest
。これは、より読みやすいと考えています。しかし、これは好みの問題です。