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?
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:
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
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.
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.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With