I need some help with this:
Example:
void method1{ MyObject obj1=new MyObject(); obj1.method1(); }
I want to mock obj1.method1()
in my test but to be transparent so I don't want make and change of code. Is there any way to do this in Mockito?
Mockito mock method We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.
The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called. We don't need to do anything else to this method before we can use it.
No. You just need to define your own Clock class or interface, and call clock.
The answer from @edutesoy points to the documentation of PowerMockito
and mentions constructor mocking as a hint but doesn't mention how to apply that to the current problem in the question.
Here is a solution based on that. Taking the code from the question:
public class MyClass { void method1 { MyObject obj1 = new MyObject(); obj1.method1(); } }
The following test will create a mock of the MyObject
instance class via preparing the class that instantiates it (in this example I am calling it MyClass
) with PowerMock
and letting PowerMockito
to stub the constructor of MyObject
class, then letting you stub the MyObject
instance method1()
call:
@RunWith(PowerMockRunner.class) @PrepareForTest(MyClass.class) public class MyClassTest { @Test public void testMethod1() { MyObject myObjectMock = mock(MyObject.class); when(myObjectMock.method1()).thenReturn(<whatever you want to return>); PowerMockito.whenNew(MyObject.class).withNoArguments().thenReturn(myObjectMock); MyClass objectTested = new MyClass(); objectTested.method1(); ... // your assertions or verification here } }
With that your internal method1()
call will return what you want.
If you like the one-liners you can make the code shorter by creating the mock and the stub inline:
MyObject myObjectMock = when(mock(MyObject.class).method1()).thenReturn(<whatever you want>).getMock();
If you really want to avoid touching this code, you can use Powermockito (PowerMock for Mockito).
With this, amongst many other things, you can mock the construction of new objects in a very easy way.
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