Blog logo on a black background with the words "Discover What's Next in Tech!"

JUnit MethodSource and Nested

In this article we show how parameterized tests in JUnit together with @Nested and what is the most elegant variant here.

Utility classes are used in many projects. Let's assume we have a StringUtil-class, which contains a method extractLastTrimmed contains. In reality, there would of course be many more auxiliary methods here.

Writing tests for such a class quickly results in a large number of test methods. One way to organize tests is to use @Nested. This makes it possible to group tests by method, for example, which improves readability and maintainability.

However, there is a limitation, especially when using parameterized tests that use a method as the source for their parameters (@MethodSource). Unfortunately, the method that provides the parameters is only found if the fully qualified name of the class plus the method name is specified as a string.
This is not only unsightly, but also prone to errors when renaming packages, classes or methods:

A more elegant alternative here is the use of @ArgumentsSource instead of @MethodSource. This becomes clear in the revised version of our test:

Instead of a simple static method, you now have a small class that uses the interface ArgumentsProvider implemented and the provideArguments-method.
Instead of @MethodSource is now used @ArgumentsSource and enter the name of the class there.
The minimal additional effort compared to the variant with @MethodSource pays off, as the use of @ArgumentsSource also with @Nested works and is refactoring-safe.

In my opinion, one should @MethodSource without a method name, as this magic, with which the test framework searches for the associated method, may not be known to every developer and therefore makes the readability of the tests more difficult.

The complete example can be found on github.


Learn more about software development

Matthias Fischer

About ME

Matthias Fischer has a degree in general computer science and has been working as a software developer at doubleSlash since 2006. He has cross-industry experience in IT projects and works with well-known customers such as Deutsche Post Direkt GmbH, BMW AGFederal Printing Office, ZF AG and Zeppelin Systems together. Matthias has extensive expertise in Spring Boot, Java EE and Angular. His main focus is on back-end development, but for some time now he has also been involved in front-end development with Angular. Matthias is also passionate about software quality, automated testing and agile development.

All contributions from Matthias Fischer

Learn more

Further information on our website and in our newsletter

Arrow up