Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between using @BeforeClass and using instance or static variable in JUnit 4 Java?

I'm new to unit test. About the purpose of using @Before annotation in JUnit 4. I just don't know the point of using it:

public class FoodTestCase {
    static private Food sandwich;

    @BeforeClass
    public static void initialise(){
        sandwich = new Sandwich();    
    }

}

vs

public class FoodTestCase {
    static private Food sandwich = new Sandwich();

}

What's the difference?

like image 325
mko Avatar asked Jun 12 '13 07:06

mko


People also ask

What is the purpose of the @BeforeClass annotation in JUnit?

org.junit Annotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before those of the current class, unless they are shadowed in the current class.

What is the difference between @BeforeClass and @before in JUnit?

Before and BeforeClass in JUnit The function @Before annotation will be executed before each of test function in the class having @Test annotation but the function with @BeforeClass will be execute only one time before all the test functions in the class.

What is the difference between @before and @BeforeClass annotation?

Key points in these differences are:@BeforeTest method executes only once before the first @Test method. @BeforeClass executes before each class.

Does BeforeClass have to be static?

JUnit's @BeforeClass annotation must be declared static if you want it to run once before all the @Test methods.


1 Answers

In this case it may not be necessary, as the initialization is really simple.

In case you have some logging, complex initialization or need to free some resources, you have to use @BeforeClass and @AfterClass

like image 175
StKiller Avatar answered Nov 07 '22 20:11

StKiller