如何在 Java 中模拟静态方法?

2022-01-14 00:00:00 tdd mockito java junit powermock

我有一个类 FileGenerator,我正在为 generateFile() 方法编写一个测试,该方法应该执行以下操作:

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

1) 它应该调用 BlockAbstractFactory

2) 它应该从子类方法 getBlocks()

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

3) 它应该调用一个静态方法 createFile 从一个最终的帮助类 FileHelper 传递一个字符串参数

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

4) 它应该调用blockList中每个BlockController的run方法

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

我正在使用 JUnit、Mockito 来模拟对象,并且我已经尝试使用 PowerMockito 来模拟静态类和最终类(Mockito 不这样做).

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).

我的问题是:我的第一个测试(从 BlockAbstractFactory 调用方法 getBlockList())正在通过,即使 generateBlocks().我已经在 BlockAbstractFactory 中实现了静态方法(目前返回 null),以避免 Eclipse 语法错误.

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.

如何测试静态方法是否在 fileGerator.generateBlocks() 中被调用?

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

推荐答案

我没有使用 PowerMock 的经验,但是由于您还没有得到答案,所以我只是在阅读文档以查看是否可以帮助您有点在路上.

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.

我发现您需要准备 PowerMock,以便我知道它需要准备哪些静态方法才能被模拟.像这样:

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
}

这里您可以找到更多信息.

这有帮助吗?

相关文章