Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock Object.getClass?

Tags:

java

mockito

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?

like image 238
tamuren Avatar asked Oct 30 '12 13:10

tamuren


People also ask

How do I mock only a part of an object?

Until now, you’ve mocked complete objects, but sometimes you’ll only want to mock a part of an object. Let’s say you only want to mock one method of an object instead of the entire object. You can do so by using patch.object (). For example, .test_get_holidays_timeout () really only needs to mock requests.get () and set its .side_effect to Timeout:

What is Java object getClass method?

Java Object getClass() Method. getClass() is the method of Object class. This method returns the runtime class of this object. The class object which is returned is the object that is locked by static synchronized method of the represented class. Syntax

What is a mock in Java?

The return value of dumps () is also a Mock. The capability of Mock to recursively define other mocks allows for you to use mocks in complex situations: Because the return value of each mocked method is also a Mock, you can use your mocks in a multitude of ways. Mocks are flexible, but they’re also informative.

How to get the name of the class of an object?

The Java Object getClass () method returns the class name of the object. The getClass () method does not take any parameters. Class of obj1: class java.lang.Object Class of obj2: class java.lang.String Class of obj3: class java.util.ArrayList In the above example, we have used the getClass () method to get the name of the class.


Video Answer


2 Answers

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.

like image 131
Aleksander Blomskøld Avatar answered Sep 22 '22 11:09

Aleksander Blomskøld


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.

like image 25
Mr.Eddart Avatar answered Sep 21 '22 11:09

Mr.Eddart