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.



