java - Mockito - How to spy on Invocation argument in doAnswer -


this first day writing unit tests using mockito , might have started complex exercise.

below class structure , writing tests class2.targetmethod(). class1 static method modifies passed in object instead of returning results.

class class1 {     static void dbquery(outparam out) {         // complex code fill in db results in outparam object     } }  class class2 {     void targetmethod() {         outparam p1 = new outparam1();         class1.dbquery(p1);         resultset rs = p1.getcursor();         ...     } } 

below setup tests:

@runwith(powermockrunner.class) @preparefortest({class1.class, class2.class}) public class class2test {     @before     public void setup() throws exception {          powermockito.mockstatic(class1.class);          doanswer(new answer<void>() {             @override             public void answer(invocationonmock invocation) throws exception {                 outparam result = (outparam)invocation.getarguments()[1];                 outparam spy = spy(result);                 resultset mockresult = mock(resultset.class);                 doreturn(mockresult).when(spy.getcursor());                 when(mockresult.getstring("some_id")).thenreturn("first_id","second_id");                 when(mockresult.getstring("name")).thenreturn("name1","name2");                  return null;             }         }).when(class1.class, "dbquery", any());     } } 

however tests fail exception below - due "doreturn" line.

any suggestions on problem or if approach wrong.

org.mockito.exceptions.misusing.unfinishedstubbingexception:  unfinished stubbing detected here:  e.g. thenreturn() may missing. examples of correct stubbing:     when(mock.isok()).thenreturn(true);     when(mock.isok()).thenthrow(exception);     dothrow(exception).when(mock).somevoidmethod(); hints:  1. missing thenreturn()  2. trying stub final method, naughty developer!  3: stubbing behaviour of mock inside before 'thenreturn' instruction if completed 

the syntax for:

doreturn(mockresult).when(spy.getcursor()); 

should be:

doreturn(mockresult).when(spy).getcursor(); 

by calling when spy, , not spy.getcursor(), give mockito chance temporarily deactivate getcursor can stub without calling real thing. though doesn't seem important here, mockito insists keep pattern calls when following doanswer (etc).


Comments