简体   繁体   中英

how to mock internal method call using mockito/powermockito

I am testing a method in class which in turn calls another artifacts' method and consume return value in it.

public void methodToTest()
{
      Object reply = artifactObj.anotherMethod(object);
      if(reply == null)
            return;
      Object =reply.getData();
}

I have used powermockito and know that if "anotherMethod" existed inside the same class I could have easily spied it over. But I am not sure how can I do same when method is not in same class.

My attempt-:

Object mockObject = mock(Object.class);
Object mockReply = mock(Object.class);
Mockito.when(artifactObj.anotherMethod(mockObject)).thenReturn(mockReply);

//Now call original test method 

Class c = new Class(artifactObj);
c.methodToTest(); 

doing above will always return reply = null inside original method that I am trying to test. I need some value of reply to be returned so that I can use it inside my method.

Null is returned because mocked method is never called:

In your example when mocking you are passing a mockObject as a matcher, as a result mocked response is only returned when said method is invoked using the same mockObject as a parameter. What you should do is introduce a matcher instead of it.

In example below Matchers.any(OriginalArgumentClass.class) is used, what it does is match any call to the method using any object as a parameter and return mocked reply.

Object reply = new Object();
ArtifactClass artifactObjMock = Mockito.mock(ArtifactClass.class);
Mockito.when(artifactObjMock.anotherMethod(Matchers.any(OriginalArgumentClass.class))).thenReturn(reply);

Now pass artifactObjMock to a constructor call:

Class c = new Class(artifactObjMock);
c.methodToTest(); 

This works under assumption that in your constructor you are assigning the passed value to the artifactObj field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM