tags:

views:

161

answers:

1

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?

+8  A: 

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.

Ralf Edmund
1)thanks you it is more clear now, but what about thread ?2) in this case should I add @Test in each java test ?3) is there a mean to regroup all annotaions in a function and call it for each java test ?
It is not clear from your code snippet, what happens within that background thread. But i think, that there is some server like resource that will be forked away using this construct.But normally I would expect some @AfterClass operation joining this Thread.
Ralf Edmund
in this code the aim is to launch tha GUI appli but why using these methods ,not clear for me