问题
I am new to Mockito and Play Framework, so can anyone suggest a solution for this:
I have 3 classes as follows:
I have a Play application where I am calling a helper method, which indeed calls an ApiClient, which calls an external api and fetches the results and returns CompletionStage of that result. And the helper method indeed returns the same result to the controller.
The Code is as follows.
public class MyController extends Controller{
@Inject
WSClient wsClient;
MyControllerHelper myControllerHelper;
public CompletionStage<Result> myMethod(){
myControllerHelper = new MyControllerHelper(wsClient);
myControllerHelper.helperMethod("searchWord");
}
}
public class MyControllerHelper {
WSClient wsClient;
ApiClient apiClient;
public MyControllerHelper(WSClient wsClient) {
apiClient = new ApiClient(wsClient);
}
public CompletionStage<SearchResults> helperMethod(String searchWord){
return apiClient.fetchMethod(searchWord);
}
}
class ApiClient{
WSClient wsClient;
public ApiClient(WSClient wsClient){
this.wsClient = wsClient;
}
public CompletionStage<SearchResults> fetchMethod(String searchWord){
}
}
To Mock the Controller:
public class MyControllerTest extends WithApplication {
@Override
protected Application provideApplication() {
return new GuiceApplicationBuilder().build();
}
MyControllerHelper myControllerHelperSpy;
@Test
public void testIndexWithSearchWords() {
Http.RequestBuilder request = new Http.RequestBuilder()
.method(POST)
.uri("/");
request.session(SessionHelper.SESSION_KEY, SessionHelper.SESSION_KEY);
request.header("USER_AGENT", "");
myControllerHelperSpy = spy(new MyControllerHelper());
doReturn(CompletableFuture.supplyAsync(SearchResults::new)).when(myControllerHelperSpy).fetchMethod(anyString());
verify(myControllerHelperSpy).fetchMethod(anyString());
Map<String, String[]> requestBody = new HashMap<>();
String[] searchKeyWord = new String[]{"hello world"};
requestBody.put("searchKeyword", searchKeyWord);
request.bodyFormArrayValues(requestBody);
Result result = route(app, request);
assertEquals(OK, result.status());
}
}
When I run the tests, it throws error:
Wanted but not invoked:
myControllerHelperSpy.fetchMethod(<any string>);
-> at controllers.MyController.testIndexWithSearchWords(MyControllerHelper.java:52)
Actually, there were zero interactions with this mock.
Can anyone suggest a solution to this? How to test this hierarchy with mockito? Thank You
来源:https://stackoverflow.com/questions/64636980/play-framework-java-mock-using-mockito-wanted-but-not-invoked-actually-there