How to mock static method in Java?

2019-02-18 19:08发布

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

2条回答
男人必须洒脱
2楼-- · 2019-02-18 19:45

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());
    }
查看更多
混吃等死
3楼-- · 2019-02-18 20:00

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?

查看更多
登录 后发表回答