Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance Variable in JUnit [duplicate]

I have a class that adds elements to a ArrayList (Instance Variable). When I write a test case for the class using Junit, I initialize the class only once. I do the same work in both the test cases.

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 the test cases why doesnt the list when printed in the second test case return [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 should be modified two times. But, when I print the list it prints only values modified from that test case. Can anyone please explain the behavior ?

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

like image 475
Newbie Avatar asked May 02 '17 04:05

Newbie


Video Answer


1 Answers

The reason for the list not being updated the second time is because of the behavior of Junit. Junit creates an instance of the test class for each test. So, a new object is created for each test case and the list is reinitialized every time.

like image 181
Newbie Avatar answered Sep 19 '22 10:09

Newbie