junit4的Parameterized tests的使用方法太過費勁了,這裏介紹下如何使用JUnitParams來簡化Parameterized tests。git
@RunWith(Parameterized.class) public class FibonacciTest { @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { 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)); } }
<dependency> <groupId>pl.pragmatists</groupId> <artifactId>JUnitParams</artifactId> <version>1.1.0</version> <scope>test</scope> </dependency>
@RunWith(JUnitParamsRunner.class) public class PersonTest { @Test @Parameters({"17, false", "22, true" }) public void personIsAdult(int age, boolean valid) throws Exception { assertThat(new Person(age).isAdult(), is(valid)); } }
固然junit5也對Parameterized tests的使用進行簡化,以下:github
@ParameterizedTest @EnumSource(value = TimeUnit.class, names = { "DAYS", "HOURS" }) void testWithEnumSourceInclude(TimeUnit timeUnit) { assertTrue(EnumSet.of(TimeUnit.DAYS, TimeUnit.HOURS).contains(timeUnit)); }
若是仍是使用junit5以前的版本,那麼能夠嘗試使用JUnitParams來簡化Parameterized tests。若是你已經使用junit5,那麼恭喜你,能夠不用額外引入JUnitParams就能夠方便地進行Parameterized tests。maven