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

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

1)它应该在BlockAbstractFactory上调用静态方法getBlockImpl(FileTypeEnum)

2)它应该从子类方法getBlocks()填充变量blockList

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

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

到目前为止,我有这个空方法:

 public class FileGenerator { // private fields with Getters and Setters public void generateBlocks() { } } 

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

我的问题是:我的第一个测试(来自BlockAbstractFactory调用方法getBlockList() )正在传递,即使generateBlocks()没有实现。 我已经在BlockAbstractFactory实现了静态方法(到目前为止返回null),以避免Eclipse语法错误。

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

到目前为止,这是我的测试类:

 @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的经验,但由于你还没有得到答案,我只是在阅读文档,看看我是否可以帮助你。

我发现你需要准备PowerMock,以便我知道它需要准备哪些静态方法来进行模拟。 像这样:

 @RunWith(PowerMockRunner.class) @PrepareForTest(BlockAbstractFactory.class) // <<=== Like that public class testFileGenerator { // rest of you class } 

在这里您可以找到更多信息。

这有帮助吗?

工作范例:

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