正如我做了一些研究,我发现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."
更多推荐
发布评论