How to mock static method in Java?

余生长醉 提交于 2019-12-19 08:54:57

问题


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 static method getBlockImpl(FileTypeEnum) on BlockAbstractFactory

2) it should populate variable blockList from the subclass method getBlocks()

3) it should call a static method createFile from a final helper class FileHelper passing a String parameter

4) it should call the run method of each BlockController in the blockList

So far, I have this empty method:

public class FileGenerator {
    // private fields with Getters and Setters

    public void generateBlocks() {
    }
}

I am using JUnit, Mockito to mock objects and I've tried using PowerMockito to mock static and final classes (which Mockito doesn't do).

My problem is: my first test (calling method getBlockList() from BlockAbstractFactory) is passing, even though there is no implementation in generateBlocks(). I have implemented the static method in BlockAbstractFactory (returning null, so far), to avoid Eclipse syntax errors.

How can I test if the static method is called within fileGerator.generateBlocks()?

Here's my Test Class, so far:

@RunWith(PowerMockRunner.class)
public class testFileGenerator {
    FileGenerator fileGenerator = new FileGenerator();

    @Test
    public void shouldCallGetBlockList() {
            fileGenerator.setFileType(FileTypeEnum.SPED_FISCAL);

            fileGenerator.generateBlocks();

            PowerMockito.mockStatic(BlockAbstractFactory.class);
            PowerMockito.verifyStatic();
            BlockAbstractFactory.getBlockImpl(fileGenerator.getFileType());
    }
}

回答1:


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?




回答2:


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());
    }


来源:https://stackoverflow.com/questions/15439592/how-to-mock-static-method-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!