DrishtiService { public Response<List<Action>> fetchNewActions(String anmIdentifier, String previouslyFetchedIndex) { String anmID = URLEncoder.encode(anmIdentifier); Response<String> response = agent.fetch(drishtiBaseURL + "/actions?anmIdentifier=" + anmID + "&timeStamp=" + previouslyFetchedIndex); Type collectionType = new TypeToken<List<Action>>() { }.getType(); List<Action> actions; try { actions = new Gson().fromJson(response.payload(), collectionType); } catch (JsonSyntaxException e) { return new Response<List<Action>>(failure, new ArrayList<Action>()); } return new Response<List<Action>>(response.status(), actions == null ? new ArrayList<Action>() : actions); } DrishtiService(HTTPAgent agent, String drishtiBaseURL); Response<List<Action>> fetchNewActions(String anmIdentifier, String previouslyFetchedIndex);  }
@Test public void shouldFetchAlertActions() throws Exception { when(httpAgent.fetch(EXPECTED_URL)).thenReturn(new Response<String>(ResponseStatus.success, IOUtils.toString(getClass().getResource("/alerts.json")))); Response<List<Action>> actions = drishtiService.fetchNewActions("anm1", "0"); verify(httpAgent).fetch(EXPECTED_URL); assertEquals(asList(actionForCreateAlert("Case X", normal.value(), mother.value(), "Ante Natal Care - Normal", "ANC 1", "2012-01-01", "2012-01-11", "1333695798583"), actionForCloseAlert("Case Y", "ANC 1", "2012-01-01", "1333695798644")), actions.payload()); assertEquals(ResponseStatus.success, actions.status()); }
@Test public void shouldFetchNoAlertActionsWhenJsonIsForEmptyList() throws Exception { when(httpAgent.fetch(EXPECTED_URL)).thenReturn(new Response<String>(ResponseStatus.success, "[]")); Response<List<Action>> actions = drishtiService.fetchNewActions("anm1", "0"); assertTrue(actions.payload().isEmpty()); }
@Test public void shouldFetchNoAlertActionsWhenHTTPCallFails() throws Exception { when(httpAgent.fetch(EXPECTED_URL)).thenReturn(new Response<String>(ResponseStatus.failure, null)); Response<List<Action>> actions = drishtiService.fetchNewActions("anm1", "0"); assertTrue(actions.payload().isEmpty()); assertEquals(ResponseStatus.failure, actions.status()); }
@Test public void shouldURLEncodeTheANMIdentifierPartWhenItHasASpace() { String expectedURLWithSpaces = "http: when(httpAgent.fetch(expectedURLWithSpaces)).thenReturn(new Response<String>(ResponseStatus.success, "[]")); drishtiService.fetchNewActions("ANM WITH SPACE", "0"); verify(httpAgent).fetch(expectedURLWithSpaces); }
@Test public void shouldReturnFailureResponseWhenJsonIsMalformed() { String expectedURLWithSpaces = "http: when(httpAgent.fetch(expectedURLWithSpaces)).thenReturn(new Response<String>(ResponseStatus.success, "[{\"anmIdentifier\": \"ANMX\", ")); Response<List<Action>> actions = drishtiService.fetchNewActions("ANMX", "0"); assertTrue(actions.payload().isEmpty()); assertEquals(ResponseStatus.failure, actions.status()); }