How to mock static method in Java?

前端 未结 2 649
一生所求
一生所求 2021-01-13 17:17

I have a class FileGenerator, and I\'m writing a test for the generateFile() method that should do the following:

1) it should call the sta

相关标签:
2条回答
  • 2021-01-13 17:31

    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());
        }
    
    0 讨论(0)
  • 2021-01-13 17:52

    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?

    0 讨论(0)
提交回复
热议问题