I was going through the documentation for junit tests but am unable to understand the need for defining tests as public.Could anyone share some info on this?
I read on https://github.com/junit-team/junit/blob/master/src/main/java/org/junit/Test.java
But am still not clear with the reason.
With is I meant why can't I write something as
@Test
private void testAdd(){ }
Question11: What happens if a Junit test method is declared as “private”? Answer: If a Junit test method is declared as “private”, the compilation will pass ok. But the execution will fail. This is because Junit requires that all test methods must be declared as “public”.
Junit is open source testing framework developed for unit testing java code and is now the default framework for testing Java development. It has been developed by Erich Gamma and Kent Beck. It is an application programming interface for developing test cases in java which is part of the XUnit Family.
Since you can call a JUnit runner to run a test case class as a system command, explicit main () for a Junit test case is not recommended. junit.textui.TestRunner.run () method takes the test class name as its argument. This method automatically finds all class methods whose name starts with test. Thus it will result in below mentioned findings:
In JUnit 5, we can use @TestMethodOrder to control the execution order of tests. We can use our own MethodOrderer, as we'll see later, or we can select one of three built-in orderers: 2.1. Using the @Order Annotation We can use the @Order annotation to enforce tests to run in a specific order.
"Test classes, test methods, and lifecycle methods are not required to be public, but they must not be private."
Ref. the doc: https://junit.org/junit5/docs/current/user-guide/#writing-tests-classes-and-methods
The JUnit framework calls your test methods from outside your test class. If your test methods are private, it won't be able to do that.
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