Instance variable in JUnit

I have a class that adds items to an ArrayList (instance variable). When I write a test case for a class using Junit, I initialize the class only once. I am doing the same job in both tests.

public class Solution {

    List<String> list = new ArrayList<String>();

    public void modifyList() {
        list.add("A");
        list.add("B");
        list.add("C");
    }
}

      

SolutionTest.java

public class TestSolution {

    Solution sol = new Solution();

    @Test
    public void testModifyList1() {
        sol.modifyList();
        Assert.assertEquals(3, sol.list.size());
        System.out.println(sol.list);
    }

    @Test
    public void testModifyList2() {
        sol.modifyList();
        Assert.assertEquals(3, sol.list.size());
        System.out.println(sol.list);
    }
}

      

When I print the list in both test cases, why is the list printed in the second test case not returned [A, B, C, A, B, C]

. Why does it just return [A, B, C]

. My understanding is that the class is initialized only once, so there is only one copy of the list and it needs to be changed two times. But when I print the list, it only prints the values ​​changed from this test case. Can anyone explain the behavior?

When I call the same method on the same object in two different test cases, why isn't this list updated twice?

+3


source to share


2 answers


The reason for list

not updating a second time is because of the behavior Junit

. Junit

creates an instance of a test class for each test. This way, a new object is created for each test case and list

reinitialized each time.



+6


source


JUnit instantiates the test class once for each test method. This means that the list will be created once per test no matter where you declare it.



+1


source







All Articles