Issue
I have a question when I was using JUnit 4. There is one thing really confused me. Why does the following has no main function, but it can be executed and give the testing result back? It does not even extend a class. So confused.... The code are as followed:
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ ATest.class,BTest.class })
public class AllTests {
}
Solution
The main method (not function) is implemented in the runner class. The runner class is invoked by the IDE or the build tool, then the runner loads the Test classes and executes all the methods that are marked (ie. by @Test annotation).
The lifecycle of a test is a bit more complex than a main function. You can have a preparation (@BeforeClass and @Before annotated methods) before to execute each @Test, then a clean up (@After and @AfterClass annotated methods).
This framework gives you more flexibility than just having a single main method. Also annotated tests can be ran individually: you may have a huge test suite, but you may want to run just a failing test repeatedly while correcting a bug; this cannot be done with a main method (unless you have a main method for every test).
There are several advantages in using a framework like JUnit over plain Java classes with a main, as you can see.
Answered By - Luigi R. Viggiano