简体   繁体   English

我如何模拟Object.getClass?

[英]How do I mock Object.getClass?

I'm working on a Java project want to write a unit test for an .equals method I have in a DTO. 我正在研究一个Java项目想要为DTO中的.equals方法编写单元测试。 In the .equals method, there is a .getClass() method called by both objects under test. 在.equals方法中,有一个.getClass()方法被两个被测对象调用。 I want to mock this, but I can't tell what type of object it wants. 我想嘲笑这个,但我不知道它想要什么类型的对象。 I tried, 我试过了,

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的返回类型是什么,我该如何操作它?

As Object.getClass() is final, you cannot mock that method with Mockito. 由于Object.getClass()是final,因此您无法使用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. 如果那是不可能的,你可以尝试使用powermock ,在那里你可以模拟任何最终方法。 Object.getClass() is a bit special, so be sure to set MockGateway.MOCK_GET_CLASS_METHOD = true in powermock. Object.getClass()有点特殊,所以一定要在powermock中设置MockGateway.MOCK_GET_CLASS_METHOD = true

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 . 你可以在https://github.com/powermock/powermock上模拟staticfinal方法(就像这个)甚至private方法和Powermock(它是一个非常酷的工具;)。

You can use it with Mockito as explained in the Mockito wiki article . 您可以将其与Mockito一起使用,如Mockito wiki文章中所述 There you will find some useful examples. 在那里你会发现一些有用的例子。

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

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