I do not like to introduce Unit tests into an outdated code base, but I have to do it.
So far, I have successfully introduced unit testing into an outdated code base using Mockito and PowerMock. Worked fine until I met this situation:
in SUT, there are several static variables (which I mocked with PowerMock, mocking static methods, and mocking constructors).
Now everything worked fine in the first test method, and the mocked static var returned the expected output value. But, but in subsequent testing methods, the mocking static object always returns the value that was set in the first test, although I call it reset () before testing.
// legacy code base: public class SUT { private static Collaborator1 c1 = null; private static Collaborator2 c2 = null; public SUT(param1) { if (c1 == null) { c1 = Collaborator1.instance(param1); c2 = new Collaborator2(c1); } else { } } } // newly introduced unit tests: @RunWith(PowerMockRunner.class) @PrepareForTest({ SUT.class, // to mock: new Collaborator2(..), as required by PowerMock when mocking constructors Collaborator1.class, // to mock: Collaborator1.instance(..), as required by PowerMock in mocking static methods }) public class SUTTest { private SUT sut; private Collaborator1 c1 = mock(Collaborator1.class); private Collaborator2 c2 = mock(Collaborator2.class); @Before public void setup() { // mock c1: PowerMockito.mockStatic(Collaborator1.class); when(Collaborator1.instance(param1)).thenReturn(c1); // mock c2: PowerMockito.whenNew(Collaborator2.class).withArguments(c1).thenReturn(c2); reset(c1); reset(c2); sut = new SUT(param1); } @Test public void test1() { when(c2.foo(input1)).thenReturn(out1); // do something } @Test public void test2() { when(c2.foo(input2)).thenReturn(out2); // BANG!!! c2.foo(input2) always return "out1" // do something } }
Since the SUT constructor only creates instances of c1 and c2, if the static c1 is null, they (c1, c2) do not get to re-create the instances in subsequent calls. I do not understand why reset (c1), reset (c2) do not affect test2?
Any idea?
source share