jeudi 27 août 2015

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?

Aucun commentaire:

Enregistrer un commentaire