Search code examples
javajmockit

MyClass stays mocked between two tests


I have two test classes, MyFirstTest and MySecondTest. Running each independently works fine. When I run both (in eclipse select the test folder which contains these files, right click, run as junit), MySecondTest fails because MyClass is still mocked when it runs its' tests. MyFirstTest requires MyClass to be mocked. MySecondTest requires MyClass to not be mocked. I thought the tearDownMocks was suppose to 'demock' the classes.

public class MyFirstTest {
    @Before
    public void setUp() throws Exception {
        Mockit.setUpMocks(MockMyClass.class);
    }
    @After
    public void tearDown() throws Exception {
        Mockit.tearDownMocks(MockMyClass.class);
    }
    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        Mockit.tearDownMocks(MockMyClass.class);
    }
    @MockClass(realClass = MyClass.class, stubs = "<clinit>")
    public static class MockMyClass {
...


public class MySecondTest {

Solution

  • The right way to do it is like mentioned below: Mock the class and assign it to a variable. And then, using that variable, you can destroy or clear the mock so that it doesn't impact any other test case.

    MockUp<PmRequestData> mockpmreq = new MockUp<PmRequestData>() {
            @Mock
            public Map<String, KPIData> getKpiDataMap() {
                return datamap;
                }
            };
    mockpmreq.tearDown();