Reputation: 691
I found my method using ReflectionUtils
Method myMethod=ReflectionUtils.findMethod(myMockClass.getClass(), "myMethod", myArg.class)
Now I would like to drive this method to return a specified value. Normally, if myMethod
would be public I would write for instance
given(myMockClass.myMethod(myArg)).willReturn(5)
But is there any possibility to do it with private myMethod?
When I've called
given(myMethod.invoke(myClass, myArg)).willReturn(5)
I've got java.lang.reflect.InvocationTargetException. I've read about PowerMock, but I would like to know whether it's possible with Mockito only
Edit:
public int A(args){
int retValue;
... some code here, the most important part
retValue=..
if(some case)
retValue= myMethod(args);
return retValue;
}
Upvotes: 2
Views: 1036
Reputation: 10817
Consider using Guava's @VisibleForTesting
annotation here. Basically, just increase the visibility of the method to the minimal level necessary to test it.
For example, if your original method is:
private int calculateMyInt() {
// do stuff
return 0;
}
Your new method would be:
@VisibleForTesting // package-private to call from test class.
int calculateMyInt() {
// do stuff
return 0;
}
Upvotes: 2
Reputation: 581
Don't hesitate to change the method visibility to package protected, even if it's only for testing purpose (typically because you want to test the method or because you want to mock it). You should clearly indicate that fact though, a good way is by using an annotation (see this answer).
Upvotes: 1
Reputation: 9374
I would recommend you not to do it. If you need to mock behavior of private method then you have problems with your design. Your class is not testable.
As workaround will be to make your method package private, and test it within same package. This will work, but also not considered as good practice.
I would recommend to read this latest Uncle's bob article
Upvotes: 1