I just want to know why the test cases (test methods) should be public like this
public class SpiceLoginTest {
@Test
public void testShouldVerifyLoginRequest() {
}
}
but if I remove public access specifier from this method
@Test
void testShouldVerifyLoginRequest() {
}
Output: java.lang.Exception: Method testShouldVerifyLoginRequest() should be public
so
What is happening behind the scenes?
Is it using reflection or what?
JUnit 4 requires that all test methods are public and don't return anything.
If a JUnit test method is declared as "private", it compiles successfully. But the execution will fail. This is because JUnit requires that all test methods must be declared as "public".
2.3. Test classes, test methods, and lifecycle methods are not required to be public , but they must not be private .
Why do we use JUnit testing? JUnit testing is used to test the behavior of methods inside classes we have written. We test a method for the expected results and sometimes exception-throwing cases—whether the method is able to handle the exceptions in the way we want.
Yes, the test runner is using reflection behind the scenes to find out what your test methods are and how to call them.
If the methods were not public
, calling them might fail (because the SecurityManager gets to veto that).
This is almost certainly because JUnit creates some main
class which calls all of your test methods for you. To call them, they need to be public.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With