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

编程入门 行业动态 更新时间:2024-10-25 16:17:46
本文介绍了如何在 Java 中模拟静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个类 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 }

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

这有帮助吗?

更多推荐

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

本文发布于:2023-10-31 04:03:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544942.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   方法   如何在   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!