I am spying on an object of class DownloadTask(which is an android async task). In the spied object, I am calling methods downloadTask.execute(url); These methods help me execute the "doInBackground()" and "onPostExecute()" of the downloadTask object. Inside the doInBackground(), I am creating a "HttpURLConnection" object, to which I pass a url(kinda like a factory method), On the returned object, In the test, I am "verifying" if "getInputStream" is getting called on it. I see from the test that I have written that I am "verifying" if the method is called on a different object(hence the failure). Can you please suggest me a way to mock the method, so that I can "verify" on the appropriate object. I have attached Code snippets below:
DownloadTaskTest.Java
=============================================================
@Test
public void execute_shouldOpenInputStreamOfConnection() throws IOException{
HttpURLConnection connectionMock = setMockConnection();
Mockito.verify(connectionMock).getInputStream();
}
private HttpURLConnection setMockConnection() throws IOException {
HttpURLConnection connectionMock = Mockito.mock(HttpURLConnection.class);
Mockito.doReturn(connectionMock).when(downloadTask).createConnection(Mockito.any(URL.class));
return connectionMock;
}
---------------------------------------------------------------------------------------------------------------------------
DownloadTask.Java
==============================================================
public class DownloadTask extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... params) {
URL url = null;
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = this.createConnection(url);
input = connection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
public HttpURLConnection createConnection(URL url) throws IOException {
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
return connection;
}
}
}
Thanks
Vineeth BS