I am using PowerMock to try and mock a final class with static methods, but whenever my code calls MyClass.getInstance()
it returns null
In my tests I have annotated the test class
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
In my method to make the mock I do the following
suppressConstructor(MyClass.class);
PowerMock.mockStatic(MyClass.class);
mockClass = PowerMock.createMock(MyClass.class);
expect(MyClass.getInstance()).andReturn(mockClass);
Should PowerMock.createMock
create an EasyMock
class?
When I call this in my code (MyClass.getInstance()
), it always returns null
but if I step through the test class the variable mockClass
gets instantiated.
It seems like you using the EasyMock way of mocking. Have you replayed the MyClass before calling the getInstance()
method, e.g.
PowerMock.replay(MyClass.class);
?
From the PowerMock MockStatic documentation:
Use PowerMock.mockStatic(ClassThatContainsStaticMethod.class) to mock all methods of this class. Use PowerMock.replay(ClassThatContainsStaticMethod.class) to change the class to replay mode. Use PowerMock.verify(ClassThatContainsStaticMethod.class) to change the class to verify mode.