嘲笑静态方法(Mocking Static Methods)

系统教程 行业动态 更新时间:2024-06-14 16:59:47
嘲笑静态方法(Mocking Static Methods)

正如我做了一些研究,我发现PowerMock能够嘲笑静态java方法。

有人能够从技术上解释PowerMock与JUnit以及其他不能或不可以的不同吗? 另外,为什么静态方法试图模拟时会引起问题?

谢谢

As i did some research i have found out that PowerMock is able to mock static java methods.

Can someone explain (technically) what is PowerMock doing different than JUnit and others which can not or do not? And also why static methods are(were) causing issues when they are tried to mock?

thanks

最满意答案

http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/

为了模拟一个实例方法,你可以简单地在一个子类中覆盖它。 你不能用静态方法来做,因为没有“静态多态性”。

Powermock可以做到这一点,因为它可以与字节码协同工作,而其他流行的框架依赖于多态性并使用CGLIB创建子类。

从链接:“基本上所有标准模拟框架使用CGLib创建一个模拟对象,这意味着它们基于分层模型(CGLib创建了一个类的子类,以在运行时测试这是实际的模拟对象)而不是PowerMock通过委托给MockGateway通过其字节码操作使用的委托模型。“

http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/

In order to mock an instance method, you can simply override it in a subclass. You can't do that with static methods because there's no "static polymorphism".

Powermock can do it because it works with bytecode, while other popular frameworks rely on polymorphism and create subclasses with CGLIB.

From the link: "Basically all standard mock frameworks use CGLib to create a mock object which means that they're based on a hierarchical model (CGLib creates a sub class of the class to test at run-time which is the actual mock object) instead of a delegation model which PowerMock uses through it's byte-code manipulation by delegating to the MockGateway."

更多推荐

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

发布评论

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

>www.elefans.com

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