user281070
user281070

Reputation: 1351

how to understand @Test & @BeforeClass?

I am beginning with JUnit and do not understand the annotations @Test and @BeforeClass.
I have the following code:

public class Toto { 
@BeforeClass
    public static void setupOnce() {
        final Thread thread = new Thread() {
            public void run() {
                Main.main(new String[]{"-arg1", "arg2"});
            }
        };
        try {
            thread.start();
        } catch (Exception ex) {
        }
    }

Why @BeforeClass? And what's the setupOnce() and threads in this case?
Should we add @Test before each Java test?
So if I have 30 Java tests, should I have @Test public void test() in each Java file?

Upvotes: 2

Views: 11534

Answers (1)

Ralf Edmund
Ralf Edmund

Reputation: 1035

The @BeforeClass Annotation identifies a method, that should be executed prior any tests cases contained in this implementation unit. In this special case, this test class contains some initialization of a threaded resource that is required to be executed in the background during the tests.

JUnit defines four lifecycle events:

  • @BeforeClass: before any other test from the class will be excuted.
  • @Before: executed directly before ONE test will be run, it will be called exactly once for any @Test annotated method.
  • @Test: the test itself, you may have several methods annotated in this way in your application.
  • @After: after the test has been executed, independently of any error or failure. There will be several executions, one for any @Test annotated method.
  • @AfterClass: after any test of this class has been executed,

In my applications i normally execute expensive initializations using a @BeforeClass annotated method while the really expensive ones even are executed only once for the complete test suite at whole. But this "event" is based on some hacks which speed up my developments.

Upvotes: 16

Related Questions