如何在 Java 1.4 中模拟静态方法?
I'm using JUnit with Mockito. PowerMock can mock static methods but it doesn't seem to be possible to use it with Java 1.4, specially since it needs annotations.
Is there any other alternative?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
(这里无耻的自我推销)
有一个项目 PowerMock-Legacy 可以让您使用Java 1.4 中的 PowerMock。它有点冗长,并且并非支持所有功能,但可能值得一试。
(Shameless self promotion here)
There is a project PowerMock-Legacy that lets you use PowerMock in Java 1.4. It is a bit verbose, and not all functionality is supported, but may worth a try.
就我个人而言,我更喜欢尽量减少模拟的使用。如果静态方法在您的代码中,我会修改它以使其更适合单元测试。也许它不应该是静态的。或者,如果必须如此,也许您可以使用设置方法来确定静态方法的行为方式。
如果静态方法不在您的代码中,那么您可能不走运。
Personally, I prefer minimizing my use of mocks. If the static method is in your code, I'd modify it to make it more unit test friendly. Maybe it shouldn't be static. Or if it has to be, maybe you could use a setup method that determines how the static method behaves.
If the static method is not in your code, you're probably out of luck.
尝试 jMockit 并仔细检查是否可以重构代码(或者是遗留代码?) 。 Mockito 谈论模拟静态方法
另请检查这篇相关帖子,尤其是乔恩的回答。
Try jMockit and double check if you can refactor the code (or is it legacy code?). Mockito says about mocking static Methods
Check also this related post especially Jon's answer.