Junit behavior is that it creates a new instance of a class for every test case. The same way @Before is executed once before each test case.
Why do we need @Before when junit initializes the global variables for each test case.
Check the example below. What is the difference between code1 and code2.
Ex:
Code1
public class MyTest{
int count = 1;
@Test
public void test1(){
count++;
assertEquals(2, count);
}
@Test
public void test2(){
count++;
assertEquals(2, count);
}
}
Code2
public class MyTest{
private int count;
@Before
public void before(){
count=1;
}
@Test
public void test1(){
count++;
assertEquals(2, count);
}
@Test
public void test2(){
count++;
assertEquals(2, count);
}
}
You're correct that it isn't needed. Both of your examples are equivalent.
There's an argument for @Before being syntactically prettier than initialising in fields or a constructor. It also makes it obvious to someone who doesn't know the intricacies of JUnit that the values in a Before are set for each test method call.
Here's what Martin Fowler has to say on the matter: https://martinfowler.com/bliki/JunitNewInstance.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With