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