如何在Java中模拟静态方法? [英] How to mock static method in Java?
问题描述
我有一个类 FileGenerator
,我正在为 generateFile()
方法编写测试执行以下操作:
I have a class FileGenerator
, and I'm writing a test for the generateFile()
method that should do the following:
1)它应该在 getBlockImpl(FileTypeEnum)
> BlockAbstractFactory
1) it should call the static method getBlockImpl(FileTypeEnum)
on BlockAbstractFactory
2)它应该从子类方法<$填充变量 blockList
c $ c> getBlocks()
2) it should populate variable blockList
from the subclass method getBlocks()
3)它应该调用静态方法 createFile
从最终助手类 FileHelper
传递一个String参数
3) it should call a static method createFile
from a final helper class FileHelper
passing a String parameter
4)它应该调用每个<的运行方法在blockList中code> BlockController
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来模拟的tatic和final类(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).
我的问题是:我的第一个测试(调用方法 getBlockList()
来自 BlockAbstractFactory
)正在传递,即使 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
}
此处您可以找到更多信息。
Here you can find more information.
这有帮助吗?
这篇关于如何在Java中模拟静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!