JUnit 5 @MethodSource in nested class

JUnit 5 @MethodSource in nested class

In JUnit 5, you can use the @MethodSource annotation to specify a method as a source of test arguments for parameterized tests. To use @MethodSource in a nested class, you can follow these steps:

  1. Define your nested test class. Make sure it's a static nested class (a nested class marked with the static keyword) because JUnit requires this for nested test classes.

  2. Inside the nested test class, create a static method that will serve as the data source for your parameterized test. This method must return a Stream of arguments to be used in your test cases. The method can be named anything you like.

  3. Annotate the data source method with @MethodSource. The value of the @MethodSource annotation should be the name of the method that provides the test arguments.

  4. Annotate your test method with @ParameterizedTest, and specify the value attribute to refer to the data source method.

Here's an example:

import org.junit.jupiter.api.*; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; public class MyNestedTest { @Nested class MyParameterizedTests { @ParameterizedTest @MethodSource("provideTestData") void testWithParameters(int input, int expected) { // Your test logic here Assertions.assertEquals(expected, input * 2); } static Stream<Arguments> provideTestData() { return Stream.of( Arguments.of(1, 2), Arguments.of(2, 4), Arguments.of(3, 6) ); } } } 

In this example:

  • MyNestedTest is a test class containing a nested class MyParameterizedTests.
  • testWithParameters is a parameterized test method within the nested class.
  • provideTestData is the static method annotated with @MethodSource that provides the test data as a Stream of Arguments.

When you run this test class, JUnit 5 will execute the testWithParameters method three times, once for each set of input arguments provided by the provideTestData method.

Make sure you have the JUnit 5 library properly configured in your project for this to work.


More Tags

android-camerax 3d samsung-mobile caching spring-jdbc rubygems web-services memoization windows-subsystem-for-linux try-catch

More Java Questions

More Internet Calculators

More Chemistry Calculators

More Geometry Calculators

More Biochemistry Calculators