How to mock static method in Java?

佐手、 提交于 2019-12-01 09:16:36

I have no experience with PowerMock, but since you didn't get an answer yet I'm just been reading through the documentation to see if I can help you a bit on your way.

I found that you need to prepare PowerMock so that I knows which static methods it needs to prepare to be mocked. Like so:

@RunWith(PowerMockRunner.class)
@PrepareForTest(BlockAbstractFactory.class) // <<=== Like that
public class testFileGenerator {
    // rest of you class
}

Here you can find more information.

Does that help?

Working example:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassStaticA.class, ClassStaticB.class})
public class ClassStaticMethodsTest {

    @Test
    public void testMockStaticMethod() {
        PowerMock.mockStatic(ClassStaticA.class);
        EasyMock.expect(ClassStaticA.getMessageStaticMethod()).andReturn("mocked message");
        PowerMock.replay(ClassStaticA.class);
        assertEquals("mocked message", ClassStaticA.getMessageStaticMethod());
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!