@Test public void shouldGetContents() throws Exception { StringContent stringContent = new StringContent(STRING_LANGUAGE, STRING_NAME, STRING_VALUE); StreamContent streamContent = new StreamContent(STREAM_LANGUAGE, STREAM_NAME, null, STREAM_CHECKSUM, STREAM_CONTENT_TYPE); GridSettings settings = createGridSettings("", true, true, "", 5, 1, "", "asc"); List<ResourceDto> resourceDtos = asList(new ResourceDto(streamContent), new ResourceDto(stringContent)); String expectedResponse = createResponse(new Resources(settings, resourceDtos)); when(cmsLiteService.getAllContents()).thenReturn(asList(streamContent, stringContent)); controller .perform( get( "/resource?name={name}&string={string}&stream={stream}&languages={languages}&rows={rows}&page={page}&sortColumn={sortColumn}&sortDirection={sortDirection}", "", true, true, "", 5, 1, "", "asc")) .andExpect(status().is(HttpStatus.OK.value())) .andExpect(content().type(APPLICATION_JSON_UTF8)) .andExpect(content().string(jsonMatcher(expectedResponse))); verify(cmsLiteService).getAllContents(); }
@Test public void shouldReturn400WhenInvalidTypeForGetContent() throws Exception { controller .perform(get("/resource/fooType/fooLanguage/fooName")) .andExpect(status().isBadRequest()); }
@Test public void shouldReturn400WhenInvalidTypeWhileDeleting() throws Exception { controller .perform(delete("/resource/fooType/fooLanguage/fooName")) .andExpect(status().isBadRequest()); }
@Test @ExpectedDatabase("toDoData.xml") public void addTodoWhenTitleAndDescriptionAreTooLong() throws Exception { String title = TodoTestUtil.createStringWithLength(Todo.MAX_LENGTH_TITLE + 1); String description = TodoTestUtil.createStringWithLength(Todo.MAX_LENGTH_DESCRIPTION + 1); TodoDTO added = TodoTestUtil.createDTO(null, description, title); mockMvc .perform( post("/api/todo") .contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8) .body(IntegrationTestUtil.convertObjectToJsonBytes(added))) .andExpect(status().isBadRequest()) .andExpect(content().mimeType(IntegrationTestUtil.APPLICATION_JSON_UTF8)) .andExpect(content().string(startsWith("{\"fieldErrors\":["))) .andExpect( content() .string( allOf( containsString( "{\"path\":\"description\",\"message\":\"The maximum length of the description is 500 characters.\"}"), containsString( "{\"path\":\"title\",\"message\":\"The maximum length of the title is 100 characters.\"}")))) .andExpect(content().string(endsWith("]}"))); }
@Test public void shouldGetAllEnrollments() throws Exception { CampaignEnrollment enrollment1 = new CampaignEnrollment("47sf6a", "PREGNANCY"); enrollment1.setDeliverTime(new Time(20, 1)); enrollment1.setReferenceDate(new LocalDate(2012, 1, 2)); enrollment1.setId(9001L); CampaignEnrollment enrollment2 = new CampaignEnrollment("d6gt40", "PREGNANCY"); enrollment2.setDeliverTime(new Time(10, 0)); enrollment2.setReferenceDate(new LocalDate(2012, 2, 15)); enrollment2.setId(9002L); CampaignEnrollment enrollment3 = new CampaignEnrollment("o34j6f", "CHILD_DEVELOPMENT"); enrollment3.setDeliverTime(new Time(10, 0)); enrollment3.setReferenceDate(new LocalDate(2012, 3, 13)); enrollment3.setId(9003L); when(enrollmentRestController.getAllEnrollments( CampaignEnrollmentStatus.ACTIVE.name(), null, null)) .thenReturn(new EnrollmentList(asList(enrollment1, enrollment2, enrollment3))); final String expectedResponse = loadJson("rest/enrollments/enrollmentList.json"); controller .perform(get("/enrollments/users")) .andExpect(status().is(HttpStatus.OK.value())) .andExpect(content().type(APPLICATION_JSON_UTF8)) .andExpect(content().string(jsonMatcher(expectedResponse))); verify(enrollmentRestController) .getAllEnrollments(CampaignEnrollmentStatus.ACTIVE.name(), null, null); }
@Test public void shouldReturn404WhenStringResourceNotFound() throws Exception { when(cmsLiteService.getStringContent(anyString(), anyString())) .thenThrow(new ContentNotFoundException()); controller.perform(get("/string/fooLanguage/fooName")).andExpect(status().isNotFound()); }
@Test public void shouldDeleteEnrollment() throws Exception { controller .perform( delete("/enrollments/{campaignName}/users/{externalId}", CAMPAIGN_NAME, EXTERNAL_ID)) .andExpect(status().is(HttpStatus.OK.value())); verify(enrollmentRestController).removeEnrollment(CAMPAIGN_NAME, EXTERNAL_ID); }
@Test public void shouldReturn404WhenEditingNonExistentStringResource() throws Exception { when(cmsLiteService.getStringContent(anyString(), anyString())) .thenThrow(new ContentNotFoundException()); controller .perform(post("/resource/string/fooLanguage/fooName").param("value", "fooValue")) .andExpect(status().isNotFound()); }
@Test @ExpectedDatabase("toDoData.xml") public void findById() throws Exception { mockMvc .perform(get("/api/todo/{id}", 1L)) .andExpect(status().isOk()) .andExpect(content().mimeType(IntegrationTestUtil.APPLICATION_JSON_UTF8)) .andExpect( content().string("{\"id\":1,\"description\":\"Lorem ipsum\",\"title\":\"Foo\"}")); }
@Test public void shouldReturn404WhenDeletingNonExistentResource() throws Exception { doThrow(new ContentNotFoundException()) .when(cmsLiteService) .removeStringContent(anyString(), anyString()); controller .perform(delete("/resource/string/fooLanguage/fooName")) .andExpect(status().isNotFound()); }
@Test @ExpectedDatabase("toDoData.xml") public void updateTodoWhenTodoIsNotFound() throws Exception { TodoDTO updated = TodoTestUtil.createDTO(3L, "description", "title"); mockMvc .perform( put("/api/todo/{id}", 3L) .contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8) .body(IntegrationTestUtil.convertObjectToJsonBytes(updated))) .andExpect(status().isNotFound()); }
@Test public void shouldRemoveStringContent() throws Exception { StringContent stringContent = new StringContent(STRING_LANGUAGE, STRING_NAME, STRING_VALUE); when(cmsLiteService.getStringContent(STRING_LANGUAGE, STRING_NAME)).thenReturn(stringContent); controller .perform( delete("/resource/{type}/{language}/{name}", STRING_TYPE, STRING_LANGUAGE, STRING_NAME)) .andExpect(status().is(HttpStatus.OK.value())); verify(cmsLiteService).removeStringContent(STRING_LANGUAGE, STRING_NAME); }
@Test public void shouldReturnAppStructure() throws Exception { List<CommcareApplicationJson> apps = application(); when(commcareApplicationDataService.retrieveAll()).thenReturn(apps); final String expectedResponse = objectMapper.writeValueAsString(apps); controller .perform(get("/schema")) .andExpect(status().is(HttpStatus.SC_OK)) .andExpect(content().type("application/json;charset=UTF-8")) .andExpect(content().string(expectedResponse)); }
@Test public void shouldHandleSchemaChangeRequest() throws Exception { controller .perform(get("/appSchemaChange/" + config.getName())) .andExpect(status().is(HttpStatus.SC_OK)); Map<String, Object> params = new HashMap<>(); params.put(EventDataKeys.CONFIG_DOMAIN, config.getAccountConfig().getDomain()); params.put(EventDataKeys.CONFIG_BASE_URL, config.getAccountConfig().getBaseUrl()); params.put(EventDataKeys.CONFIG_NAME, config.getName()); verify(eventRelay).sendEventMessage(new MotechEvent(SCHEMA_CHANGE_EVENT, params)); }
@Test public void shouldReturnLanguagesStartedWithGivenTerm() throws Exception { String expectedResponse = createResponse(asList(STREAM_LANGUAGE)); controller .perform( get( "/resource/available/{field}?term={term}", "language", STREAM_LANGUAGE.toLowerCase().substring(0, 2))) .andExpect(status().is(HttpStatus.OK.value())) .andExpect(content().type(APPLICATION_JSON_UTF8)) .andExpect(content().string(jsonMatcher(expectedResponse))); }
/** * Test method for {@link org.sagar.samples.controller.spring.HomeController#home()}. * * @throws Exception */ @Test public void testHome() throws Exception { System.out.println("excecuting test method 1"); HomeController homeController = new HomeController(); ModelAndView mnv = homeController.home(); assertEquals(mnv.getViewName(), "home"); assertEquals((String) mnv.getModel().get("name"), "Sagar Prasad"); // ------------MVC TESTING------------------// mockMvc .perform(MockMvcRequestBuilders.get("/home").accept(MediaType.APPLICATION_XML)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(print()); ; }
@Test public void shouldReturnStringContent() throws Exception { StringContent stringContent = new StringContent(STRING_LANGUAGE, STRING_NAME, STRING_VALUE); String expectedResponse = createResponse(stringContent); when(cmsLiteService.getStringContent(STRING_LANGUAGE, STRING_NAME)).thenReturn(stringContent); controller .perform( get("/resource/{type}/{language}/{name}", STRING_TYPE, STRING_LANGUAGE, STRING_NAME)) .andExpect(status().is(HttpStatus.OK.value())) .andExpect(content().type(APPLICATION_JSON_UTF8)) .andExpect(content().string(jsonMatcher(expectedResponse))); verify(cmsLiteService).getStringContent(STRING_LANGUAGE, STRING_NAME); }
@Test @ExpectedDatabase("toDoData.xml") public void addEmptyTodo() throws Exception { TodoDTO added = TodoTestUtil.createDTO(null, "", ""); mockMvc .perform( post("/api/todo") .contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8) .body(IntegrationTestUtil.convertObjectToJsonBytes(added))) .andExpect(status().isBadRequest()) .andExpect(content().mimeType(IntegrationTestUtil.APPLICATION_JSON_UTF8)) .andExpect( content() .string( "{\"fieldErrors\":[{\"path\":\"title\",\"message\":\"The title cannot be empty.\"}]}")); }
@Test @ExpectedDatabase( value = "toDoData-add-expected.xml", assertionMode = DatabaseAssertionMode.NON_STRICT) public void add() throws Exception { TodoDTO added = TodoTestUtil.createDTO(null, "description", "title"); mockMvc .perform( post("/api/todo") .contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8) .body(IntegrationTestUtil.convertObjectToJsonBytes(added))) .andExpect(status().isOk()) .andExpect(content().mimeType(IntegrationTestUtil.APPLICATION_JSON_UTF8)) .andExpect( content().string("{\"id\":3,\"description\":\"description\",\"title\":\"title\"}")); }
@Test public void shouldCreateEnrollment() throws Exception { controller .perform( post("/enrollments/{campaignName}/users", CAMPAIGN_NAME) .contentType(MediaType.APPLICATION_JSON) .param("externalId", EXTERNAL_ID) .param("enrollmentId", "9001")) .andExpect(status().is(HttpStatus.OK.value())); ArgumentCaptor<EnrollmentRequest> captor = ArgumentCaptor.forClass(EnrollmentRequest.class); verify(enrollmentRestController) .enrollOrUpdateUser(eq(CAMPAIGN_NAME), eq(EXTERNAL_ID), captor.capture()); assertEquals(DateUtil.today(), captor.getValue().getReferenceDate()); assertEquals(new Long(9001L), captor.getValue().getEnrollmentId()); }
@Test public void shouldReturnNamesStartedWithGivenTerm() throws Exception { StringContent stringContent = new StringContent(STRING_LANGUAGE, STRING_NAME, STRING_VALUE); StreamContent streamContent = new StreamContent(STREAM_LANGUAGE, STREAM_NAME, null, STREAM_CHECKSUM, STREAM_CONTENT_TYPE); String expectedResponse = createResponse(asList(STRING_NAME)); when(cmsLiteService.getAllContents()).thenReturn(asList(streamContent, stringContent)); controller .perform(get("/resource/available/{field}?term={term}", "name", "valid-stri")) .andExpect(status().is(HttpStatus.OK.value())) .andExpect(content().type(APPLICATION_JSON_UTF8)) .andExpect(content().string(jsonMatcher(expectedResponse))); verify(cmsLiteService).getAllContents(); }
@Test public void shouldEditStringContent() throws Exception { StringContent stringContent = new StringContent(STRING_LANGUAGE, STRING_NAME, STRING_VALUE); when(cmsLiteService.getStringContent(STRING_LANGUAGE, STRING_NAME)).thenReturn(stringContent); controller .perform( post("/resource/string/{language}/{name}", STRING_LANGUAGE, STRING_NAME) .param("value", "new value")) .andExpect(status().is(HttpStatus.OK.value())); ArgumentCaptor<StringContent> captor = ArgumentCaptor.forClass(StringContent.class); verify(cmsLiteService).addContent(captor.capture()); stringContent.setValue("new value"); assertEquals(stringContent, captor.getValue()); }
@Test public void shouldReturn500WhenFailedToScheduleJobForEnrollment() throws Exception { MessageCampaignException.MessageKey message = new MessageCampaignException.MessageKey( "msgCampaign.error.schedulingError", Arrays.asList(EXTERNAL_ID)); doThrow(new SchedulingException(EXTERNAL_ID, null)) .when(enrollmentRestController) .enrollOrUpdateUser(any(String.class), any(String.class), any(EnrollmentRequest.class)); controller .perform( post("/enrollments/{campaignName}/users", CAMPAIGN_NAME) .contentType(MediaType.APPLICATION_JSON) .param("externalId", EXTERNAL_ID) .param("enrollmentId", "9001")) .andExpect(status().is(HttpStatus.INTERNAL_SERVER_ERROR.value())) .andExpect(content().string(jsonMatcher(GSON.toJson(message)))); }
@Test public void shouldReturn400WhenTryingToEnrollEnrolleeToFinishedCampaign() throws Exception { MessageCampaignException.MessageKey message = new MessageCampaignException.MessageKey( "msgCampaign.error.campaignAlreadyEnded", Arrays.asList(CAMPAIGN_NAME)); doThrow(new CampaignAlreadyEndedException(CAMPAIGN_NAME, null)) .when(enrollmentRestController) .enrollOrUpdateUser(any(String.class), any(String.class), any(EnrollmentRequest.class)); controller .perform( post("/enrollments/{campaignName}/users", CAMPAIGN_NAME) .contentType(MediaType.APPLICATION_JSON) .param("externalId", EXTERNAL_ID) .param("enrollmentId", "9001")) .andExpect(status().is(HttpStatus.BAD_REQUEST.value())) .andExpect(content().string(jsonMatcher(GSON.toJson(message)))); }
@Test public void testCropImage() throws Exception { mockMvc.perform(post("/image/crop")).andExpect(status().isOk()); verify(imageService, timeout(1)).cropImage(); }
@Test public void shouldReturn400WhenInvalidFieldForAvailableFields() throws Exception { controller.perform(get("/resource/available/fooField")).andExpect(status().isBadRequest()); }
@Test @ExpectedDatabase("toDoData.xml") public void findByIdWhenTodoIsNotFound() throws Exception { mockMvc.perform(get("/api/todo/{id}", 3L)).andExpect(status().isNotFound()); }