How do I mock Object.getClass?

11,882

Solution 1

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.

Solution 2

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.

Share:
11,882

Related videos on Youtube

tamuren
Author by

tamuren

Updated on September 15, 2022

Comments

  • tamuren
    tamuren over 1 year

    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?