java - Mockito: mock both return value with callback method -
this question has answer here:
- calling callbacks mockito 3 answers
in mockito, want mock method returns value , has invoke callback
for example, here service method:
string fetchstring(callback<string> callback);
i want return value happen before callback invoked. looked using mockito.doanswer(..)
can't seem figure out how make method invoke callback after return statement. example:
when(mockservice.fetchstring(any(callback.class)).thenanswer( new answer<string>() { string answer(invocationonmock invocation) { ((callback<string>) invocation.getarguments()[0]).onresult("callback string"); return "return string"; } });
as can see in example above: callback invoked before value returned. does't test asynchronous callbacks properly. there way make callback method called after value returned?
i know argumentcaptor can used here, there alternative doesn't involve manually calling callback?
something combination of doanswer(..)
, thenreturn(..)
?
the best way achieve use argumentcaptor
, mentioned @talex.
the way used is:
service method:
string fetchstring(callback<string> callback);
junit test:
argumentcaptor<callback> captor = argumentcaptor.forclass(callback.class); when(mockservice.fetchstring(captor.capture()).thenreturn("return string"); string answer = mockservice.fetchstring(callbacktotest); // callback invoked after service method returned value captor.getvalue().onresult("callback string"); assertequals("return string", answer); verify(callbacktotest).onresult(eq("callback string"));
Comments
Post a Comment