简体   繁体   English

如何模拟来自第三方库的类的静态调用

[英]How to mock a static call on a class from a third-party library

I am wondering whether it is possible with PowerMock or any other library to mock out a static call in a class from a library. 我想知道PowerMock或任何其他库是否有可能模拟库中类的静态调用。 The class in that third-party library makes a call to one of the classes in the rt.jar and I want a return a custom implementation of that returned Type . 该第三方库中的类对rt.jar中的一个类进行了调用,我想返回该返回的Type的自定义实现。 I am trying to do this outside of test code. 我正在尝试在测试代码之外执行此操作。

Otherwise, I had to extend a few classes from that library and replace some implementation. 否则,我必须从该库中扩展一些类并替换一些实现。 Has someone done anything like this before? 有人做过这样的事吗?

Yes it is possible, eg using PowerMock.mockStatic() or PowerMock.mockStaticPartial() if you want to mock one method, only. 是的,这是可能的,例如,如果您只想模拟一个方法,则可以使用PowerMock.mockStatic()PowerMock.mockStaticPartial()

There is a quite good tutorial on the homepage of PowerMock. PowerMock主页上有一个很好的教程。

I posted an example on SO . 在SO上发布了一个示例

[EDIT] IF you want to do such magic in production code, however, I would recommend NOT to use a Testing-Framework. [编辑]如果您想在生产代码中做这样的魔术,但是,我建议您不要使用测试框架。 Maybe Groovy can help you with that - it is possible with Groovy to manipulate classes (even JDK classes) at runtime, and it is (I think) a thinner layer on top of the JVM. 也许Groovy可以为您提供帮助-Groovy可以在运行时操作类(甚至JDK类),并且(我认为)它是JVM上较薄的一层。

Generally speaking it's really bad idea to do such hardcore stubbing (it's not mocking what you describe). 一般来说,进行这样的硬核存根是一个非常糟糕的主意(这并不是在嘲笑您的描述)。 I'd go with building tiny abstraction over this library so that you can have full control on what you want to return. 我将在此库上构建微小的抽象,以便您可以完全控制要返回的内容。 It is possible to use some features of PowerMock outside tests but this not piece of cake. 可以在外部测试中使用PowerMock的某些功能,但这并不是小菜一碟。 Here you have rough description that can help if you really want: https://groups.google.com/d/msg/powermock/SMDMe-y6fLg/1HF0TsGOqTIJ 在这里,您可以得到粗略的描述,如果您确实需要的话可以提供帮助: https : //groups.google.com/d/msg/powermock/SMDMe-y6fLg/1HF0TsGOqTIJ

Anyway I would not recommend doing that. 无论如何,我不建议您这样做。

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

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