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?
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
Suppose, you had all of your Food related data (say a Menu) setup at the backend in a database table. Your Food test cases could then pertain to updating the Menu (all the CRUD ops basically).
Instead of opening a DB connection for every test case (using
@Before
); it would be wise if you do it just once before you run all your test cases via a method marked@BeforeClass
.Now the use of a method makes sense as the setup would most probably be slightly complex (you may decide to use a Spring container to get your
Connection
from aDataSource
) and you would not be able to achieve it with a single line where you declare yourConnection
object.Similarly, you would use the
@AfterClass
to tear down your global setup (for all the test cases) i.e. closing your database connection here.Inheritance adds another wrinkle:
Let's say you have two JUnit tests that extend a common base class. And let's say the base class has both a static initializer block and a
@BeforeClass
method. In this case, the static initializer block will run once, while the@BeforeClass
method will run twice.So, if you have a very expensive computation or resource that you need set up across a whole suite of test cases that share a common base class, then you could use the static initializer block for that.
I think the idea is like that: You use @AfterClass to free resources. Then it is logical to have @BeforeClass to acquire them. Because it may not be a good idea to let developer to guess that he need to use static block.
Almost no difference. But if constructor of
Sandwich
throws exception you cannot initialize it directlystatic private Food sandwich = new Sandwich();
but have to wrap initialization withtry/catch
block. However methodinitialise()
may be declared asthrows MyException
, so the test case will fail if exception indeed thrown during initialization.In your particular example - not much. However there is also @Before annotation which will run prior to every test in your class. Take a look at http://selftechy.com/2011/05/17/junit4-before-vs-beforeclass-after-vs-afterclass, it is explained well there.