Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit new instance vs Before

Tags:

java

junit

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); 
        }
    }
like image 422
Newbie Avatar asked Sep 29 '26 14:09

Newbie


1 Answers

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

like image 51
Sam Avatar answered Oct 01 '26 04:10

Sam