7

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 {
leppie
  • 115,091
  • 17
  • 196
  • 297
user1346730
  • 165
  • 4
  • 13
  • 1
    'Well I found that adding Mockit.tearDownMocks(); to MySecondTest classes setUp (which is annotated with Before) method, resets mocks so that it will not use the mock from the previous class. Not sure why Mockit.tearDownMocks(MockMyClass.class) invocations from inside the methods annotated with After and AfterClass are falling down...' – user1346730 Apr 20 '12 at 14:38

2 Answers2

3

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();
TT.
  • 15,774
  • 6
  • 47
  • 88
Aakash Goyal
  • 1,051
  • 4
  • 12
  • 44
2

The Mockit.tearDownMocks() method accepts real classes and not the mocks. So, the right code would be:

Mockit.tearDownMocks(MyClass.class);
Boris Brodski
  • 8,425
  • 4
  • 40
  • 55
  • 3
    This feature is deprecated. You now must call `.tearDown` on the mock class. Also, in JUnit this should be done between tests automatically – keaplogik Feb 09 '15 at 18:06