I am trying to mock a method whose signature is :
public A doSomething(B b, String str){}
I tried to update str value by using doAnswer. However this method returns object A with values set conditionally. I am not able to find out a way to set specific str value to be passed to this method. Can anyone please let me know how this can be achieved? I cannot use powermock in my project.
For one-off mocks, you can use InvocationOnMock.getArguments
to get the value of str
:
doAnswer(new Answer<Foo>() {
@Override public Foo answer(InvocationOnMock invocation) {
A a = mock(A.class);
when(a.someMethod()).thenReturn((String) (invocation.getArguments()[0]));
return a;
}
}).when(yourObject).doSomething(any(B.class), anyString());
// or with Java 8:
doAnswer(invocation => {
A a = mock(A.class);
when(a.someMethod()).thenReturn((String) (invocation.getArguments()[0]));
return a;
}).when(yourObject).doSomething(any(), anyString());
...but as long as the method is mockable (visible and non-final), you can also write your new method inline as an anonymous inner subclass (or a static subclass defined elsewhere), which can accomplish the same thing without so much casting and Mockito syntax:
YourObject yourObject = new YourObject() {
@Override public A someMethod(B b, String str) {
A a = mock(A.class);
when(a.someMethod()).thenReturn(str);
return a;
}
};
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