I've looked over this post but still confused. What i want to do is that when i call my mocked service i want another method to be called. Specifically let me show you the class i am mocking (and keep in mind i am trying to test a presenter class if that matters):
Here is the NewsService class i am mocking:
public class NewsService implements INewsServiceContract {
Gson gson;
Callback mCallback;
public NewsService() {
configureGson();
}
private static String readStream(InputStream in) {
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(in));) {
String nextLine = "";
while ((nextLine = reader.readLine()) != null) {
sb.append(nextLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public void setCallBack(Callback cb) {
mCallback = cb; // or we can set up event bus
}
private void configureGson() {
GsonBuilder builder = new GsonBuilder();
builder.excludeFieldsWithoutExposeAnnotation();
gson = builder.create();
}
@Override
public void loadResource() {
new AsyncTask<String, String, String>() {
@Override
protected String doInBackground(String... params) {
String readStream = "";
try {
URL url = new URL("https://api.myjson.com/bins/nl6jh");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream = readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return readStream;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
NewsService.this.onRequestComplete(result);
}
}.execute();
}
public void onRequestComplete(String data) {
data = data.replaceAll("\"multimedia\":\"\"", "\"multimedia\":[]");
news.agoda.com.sample.Model.NewsEntities newsEntities = gson.fromJson(data, NewsEntities.class);
mCallback.onResult(newsEntities);
}
}
its nothing fancy and at the end in onRequestComplete it just makes a call to a listener with the results. the listener is this case is my presenter if that matters.
In my test case i would like to verify that this call back actually took place. I have tried the following test with my mocked service:
@org.junit.Test
public void shouldDisplayResultsOnRequestComplete() throws Exception {
presenter.loadResource();
when(service.loadResource()).thenAnswer(new Answer<Object>() {
Object answer(InvocationOnMock invocation) {
//what do i do in here ?
}
});
}
all i want to test is that if someone calls service.loadResouces() then they get a call back with the results. can you help ?