Parameterized test run in JUnit Jupiter (JUnit5)

Is there a way to parameterized tests in JUnit Jupiter ( Junit5 )?

 @RunWith(Parameterized.class) 

Background:

I looked. How to write junit tests for interfaces? and wanted to implement test cases, as answered here using JUnit5. But could not find the same class / es in the Jupiter package.

Attempts:

Looking for alternatives, I found that Extensions will replace @RunWith, as indicated in Migrating Tips

@RunWith no longer exists; replaced by @ExtendWith.

I tried to define CustomExtension , as shown in the example here - MockitoExtension , but could not get the opportunity to use instances of the Parameterized classes.

Waiting for proposals for testing interfaces with parameterized class instances that implement it in Junit5 .

+5
source share
4 answers

JUnit 5 M4 has just been released and now supports parameterized tests.

Here is an example of "Hello World":

 @ParameterizedTest @ValueSource(strings = { "Hello", "World" }) void testWithStringParameter(String argument) { assertNotNull(argument); } 

For detailed documentation and additional examples, see the User Guide .

+5
source

As of January 9, 2017, JUnit 5 does not support parameterized tests as such, but is working on this feature . Note that you could achieve something similar with dynamic tests .

However, I would consider both poor ways to implement front-end tests, and JUnit Jupiter offers two best approaches:

  • @Test default methods for annotated interface will be executed . Therefore, if you have a production Interface Interface , you can write an InterfaceTest interface that uses the default methods to test everything you want. For each Impl implements Interface you can write ImplTest implements InterfaceTest .
  • If you need more flexibility and want to implement tests for Interface in the AbstractInterfaceTest abstract class, you can do this too, and then a nested test class in your ImplTest that extends AbstractInterfaceTest .

Both of these approaches ensure that the test for the interface does not know the classes that implement the interface, which is a huge drawback of the answer associated with .

+4
source

You can use dynamic tests for this:

 @TestFactory Stream<DynamicTest> params() { return Stream.of(new double[][]{{2d, 4d}, {3d, 9d}, {4d, 16d}}). map(i -> dynamicTest("Square root test " + Arrays.toString(i), () -> assertEquals(i[0], Math.sqrt(i[1])) ) ); } 
+2
source

In my projects, I used this library:

https://github.com/TNG/junit-dataprovider/

to add parameterization to my JUnit tests. I used version 4.x, but was never a fan of the built-in parameterization that he provided. If you are familiar with TestNg @DataProvider, this extension is not much different.

Check it out, see if it will bring you any benefit, as it was for me and my team. Honestly, I could not imagine how to work without him now.

+1
source

Source: https://habr.com/ru/post/1262530/


All Articles