Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Junit test cases(Methods) should be public? [duplicate]

Tags:

java

public

junit

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

  1. What is happening behind the scenes?

  2. Is it using reflection or what?

like image 737
Gurinder Avatar asked May 04 '16 06:05

Gurinder


People also ask

Should JUnit methods be public?

JUnit 4 requires that all test methods are public and don't return anything.

What happens if a JUnit test method is declared as private?

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".

Should JUnit 5 tests be public?

2.3. Test classes, test methods, and lifecycle methods are not required to be public , but they must not be private .

Why are Junits needed?

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.


2 Answers

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).

like image 117
Thilo Avatar answered Oct 09 '22 08:10

Thilo


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.

like image 1
nhouser9 Avatar answered Oct 09 '22 10:10

nhouser9