Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito Change argument value of non void method

Tags:

java

mockito

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.

like image 902
Rajesh Kolhapure Avatar asked May 22 '17 14:05

Rajesh Kolhapure


1 Answers

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;
  }
};
like image 67
Jeff Bowman Avatar answered Oct 22 '22 15:10

Jeff Bowman