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?
source to share