java 我如何模拟 Object.getClass?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13140487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I mock Object.getClass?
提问by tamuren
I'm working on a Java project want to write a unit test for an .equals method I have in a DTO. In the .equals method, there is a .getClass() method called by both objects under test. I want to mock this, but I can't tell what type of object it wants. I tried,
我正在处理一个 Java 项目,想要为 DTO 中的 .equals 方法编写单元测试。在 .equals 方法中,有一个被测试对象调用的 .getClass() 方法。我想嘲笑这个,但我不知道它想要什么类型的对象。我试过,
when(mockRoomInv.getClass()).thenReturn(RoomInv.class);
when(mockRoomInv.getClass()).thenReturn(RoomInv.class);
but sure as heck didn't do anything. What is the return type of getClass, and how do I manipulate it?
但可以肯定的是,他什么也没做。getClass 的返回类型是什么,我该如何操作它?
采纳答案by Mr.Eddart
Object.getClass()
is a final
method, so you cannot mock it with Mockito.
Object.getClass()
是一种final
方法,所以你不能用 Mockito 模拟它。
You can mock static
and final
methods (as this one) and even private
methods with Powermock (it's a quite cool tool ;) available at https://github.com/powermock/powermock.
您可以使用 Powermock模拟static
和final
方法(如这个),甚至private
方法(这是一个非常酷的工具;)可从https://github.com/powermock/powermock 获得。
You can use it with Mockito as explained in the Mockito wiki article. There you will find some useful examples.
您可以将它与 Mockito 一起使用,如Mockito wiki 文章中所述。在那里你会找到一些有用的例子。
回答by Aleksander Blomsk?ld
As Object.getClass()
is final, you cannot mock that method with Mockito. I would strongly advice you to refactor your code to inject the class in another way. If that's not possible, you could try out powermock, where you could mock any final method. Object.getClass()
is a bit special, so be sure to set MockGateway.MOCK_GET_CLASS_METHOD = true
in powermock.
由于Object.getClass()
是决赛,你不能嘲笑与该的Mockito的方法。我强烈建议你重构你的代码,以另一种方式注入这个类。如果这是不可能的,您可以尝试powermock,您可以在其中模拟任何最终方法。Object.getClass()
有点特殊,所以一定要MockGateway.MOCK_GET_CLASS_METHOD = true
在powermock里面设置。