davido
davido

Reputation: 121

JMockit - Partial mocking and mocked parent

I would like to test (using JMockit) a class that looks like this:

class MyClass extends ComplexParentClass {

    public void testedMethod() {
        ...
    }

    private int complexPrivateMethod() {
        ...
    }

}

I can't change the class. The problem is that the ComplexParentClass has a complex constructor, which makes it hard to test. So I would like to mock the parent class. I would also like to mock the complex private method. But is something like that even possible?

I tried the following:

class MyClassTest {

    @Tested
    MyClass myClass;

    // mock the parent
    @Mocked
    ComplexParentClass complexParentClass;

    @Test
    public void test() {
        new Expectations(myClass) {{
            // partially mock the private method
            Deencapsulation.invoke(myClass, "complexPrivateMethod"); result = 0;
        }};

        myClass.testedMethod();
    }

}

This leads to an "already mocked" exception though.

Does anybody have an idea how to approach this?

Upvotes: 2

Views: 3232

Answers (1)

assylias
assylias

Reputation: 328568

Have you tried using MockUps? Something like this would mock complexPrivateMethod only:

@Test public void test() {
  new MockUp<ComplexParentClass> () {
    @Mock private int complexPrivateMethod() { return 0; }
  };

  //do something with MyClass
}

Upvotes: 2

Related Questions