Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MyClass stays mocked between two tests

Tags:

java

jmockit

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 {
like image 221
user1346730 Avatar asked Apr 20 '12 13:04

user1346730


2 Answers

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();
like image 60
Aakash Goyal Avatar answered Oct 01 '22 08:10

Aakash Goyal


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

Mockit.tearDownMocks(MyClass.class);
like image 28
Boris Brodski Avatar answered Oct 01 '22 08:10

Boris Brodski