lukeg
lukeg

Reputation: 4399

Private static inner class - Powermock

I want to mock private static inner class using Powermock (based on EasyMock). This does not come from production code, it's just a question whether something is possible. I am pretty sure this is bad design, but it's something I'm trying for science.

Let's say we have a class with static private inner class:

public class Final {
    private static class Inner {
        private final int method () { return 5; }
    }

    public int callInnerClassMethod () {
        return new Inner().method();
    }
}

I would like to mock the Inner class and its method.

I have come out with the code as follows:

    Class<?> innerType = Whitebox.getInnerClassType(Final.class, "Inner");
    Object innerTypeMock = PowerMock.createMock(innerType);
    PowerMock.expectNew(innerType).andReturn(innerType);
    PowerMock.expectPrivate(innerType, "method").andReturn(42);
    PowerMock.replay(innerTypeMock);
    new Final().callInnerClassMethod();

In the code: we get the type of Inner.class and mock it, when a user creates new object of type Inner we say that we return our instance, and when someone calls its method we provide our implementation for it.

Generally, I am learning about mocking and one can be sure this code proves I don't know what I'm doing. The code does not even compile and I get the following error on the line PowerMock.expectNew(innerType).andReturn(innerType):

andReturn (capture) in IExpectationSetters cannot be applied to (java.lang.Object)

 Is the mocking of private static inner class even possible? I have not found a definitive code example on SO.

Upvotes: 0

Views: 1524

Answers (1)

lukeg
lukeg

Reputation: 4399

I have managed to get around the compile error by using bare Class innerType = ... instead of Class<?> innerType = ... in my code. It feels wrong, but works. I'd grateful if someone explained the difference and how to make it work in the original example. There were also some places where I mixed innerType and innerTypeMock. The full, working test code looks as follows:

Class innerType = Whitebox.getInnerClassType(Final.class, "Inner");
Object innerTypeMock = PowerMock.createMock(innerType);
PowerMock.expectNew(innerType).andReturn(innerTypeMock);
PowerMock.expectPrivate(innerTypeMock, "method").andReturn(42);
PowerMock.replayAll();
System.out.println(""+new Final().callInnerClassMethod());

Upvotes: 1

Related Questions