Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking methods of local scope objects with Mockito

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?

like image 881
Xoke Avatar asked Jun 29 '11 11:06

Xoke


People also ask

How do you mock an object method?

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.

Can I mock objects in Mockito?

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.

Can we mock method local variable?

No. You just need to define your own Clock class or interface, and call clock.


2 Answers

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();    
like image 103
raspacorp Avatar answered Oct 09 '22 23:10

raspacorp


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.

like image 40
Mr.Eddart Avatar answered Oct 09 '22 22:10

Mr.Eddart