In Why JUnit 5 default access modifier changed to package-private, Sam Brannen's answer mentions how there is no need for defining public methods anymore following the principle of "less is more", which explains the reasoning behind this change (I think it's great!).
However, I still don't quite understand how it is technically possible.
In Why Junit test cases(Methods) should be public? (this is about JUnit 4), the accepted answer states:
If the methods were not
public
, calling them might fail (because the SecurityManager gets to veto that).
How and why is this no longer a problem in JUnit 5 when accessing package-private/protected methods through reflection?
JUnit 5 makes more extensive use of reflection. It has more power to find classes and methods, and also to inject values non-visible (private, package-private, etc.) members. I've seen some of their code use setAccessible(true)
to make non-public fields and methods accessible.
However, this doesn't work well with the module system that was added in Java 9. You can solve that by using the --add-opens
JVM flag. For more information about that, see https://stackoverflow.com/a/71296829/1180351