How do I mock Object.getClass?

java, mockito

Solution

`Object.getClass()` is a `final` method, so you cannot mock it with 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.

You can use it with Mockito as explained in the Mockito wiki article. There you will find some useful examples.

Problem

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, `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?

Original source