简体   繁体   English

模拟静态方法

[英]Mocking Static Methods

As i did some research i have found out that PowerMock is able to mock static java methods. 正如我做了一些研究,我发现PowerMock能够模拟静态java方法。

Can someone explain (technically) what is PowerMock doing different than JUnit and others which can not or do not? 有人能解释(技术上)什么是PowerMock与JUnit不同的东西和其他不能或不能的东西? 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/ 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. Powermock可以做到这一点,因为它使用字节码,而其他流行的框架依赖于多态并使用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." 从链接:“基本上所有标准的模拟框架都使用CGLib来创建一个模拟对象,这意味着它们基于一个层次模型(CGLib创建一个类的子类,在运行时测试,这是实际的模拟对象)而不是PowerMock通过委托给MockGateway的字节码操作来使用的委托模型。“

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM