Java 类org.springframework.test.web.servlet.result.MockMvcResultHandlers 实例源码

项目:nixmash-blog    文件:PostsRestControllerTests.java   
@Test
public void moreLikeThis_DisplaySetTrue() throws Exception {

    // MoreLikeThis Posts Enabled, returns an HTML Response

    applicationSettings.setMoreLikeThisDisplay(true);
    List<Post> posts = postService.getAllPosts();
    postDocService.reindexPosts(posts);

    mockMvc.perform(get("/post/" + MLT_POSTNAME))
            .andExpect(model().attributeExists(MORELIKETHIS_ATTRIBUTE));

    MvcResult mvcResult = mockMvc.perform(get("/json/posts/post/mlt/" + MLT_POSTID))
            .andExpect(status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML))
            .andReturn();

    assertThat(mvcResult.getResponse().getContentAsString(),
            containsString("<div class=\"mlt-item\">"));

}
项目:java-rest-books    文件:BookControllerTest.java   
@Test
public void should_update_valid_book_and_return_ok_status() throws Exception {
    Book book = new Book("978-0321356680","Book updated","Publisher");
    book.setDescription("New description");

    Author author = new Author("John","Doe");
    book.addAuthor(author);

    mockMvc.perform(put("/api/books/978-0321356680")
            .contentType(MediaType.APPLICATION_JSON)
            .content(json(book)))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$.id", is(1)))
            .andExpect(jsonPath("$.title", is("Book updated")))
            .andExpect(jsonPath("$.description", is("New description")))
            .andExpect(jsonPath("$.publisher", is("Publisher")))
            .andExpect(jsonPath("$.authors[0].firstName", is("John")))
            .andExpect(jsonPath("$.authors[0].lastName", is("Doe")))
            .andDo(MockMvcResultHandlers.print());
}
项目:java-rest-books    文件:BookControllerTest.java   
@Test
public void should_not_update_unknown_book_and_return_not_found_status() throws Exception {
    Book book = new Book("978-0321356680","Book updated","Publisher");
    book.setDescription("New description");

    Author author = new Author("John","Doe");
    book.addAuthor(author);

    mockMvc.perform(put("/api/books/000-1234567890")
            .contentType(MediaType.APPLICATION_JSON)
            .content(json(book)))
            .andExpect(status().isNotFound())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$[0].logref", is("error")))
            .andExpect(jsonPath("$[0].message", containsString("could not find book with ISBN: '000-1234567890'")))
            .andDo(MockMvcResultHandlers.print());
}
项目:Learning-Spring-5.0    文件:TestAddBookController_Integration.java   
@Test
public void testAddBook() {
    try {
        mockMVC.perform(MockMvcRequestBuilders.post("/addBook.htm")

                        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                        .param("bookName", "Book_test")
                        .param("author", "author_test")
                        .param("description", "adding book for test")
                        .param("ISBN", "1234")
                        .param("price", "9191")
                        .param("publication", "This is the test publication")
                        .requestAttr("book", new Book()))
                .andExpect(MockMvcResultMatchers.view().name("display"))
                .andExpect(MockMvcResultMatchers.model().attribute("auth_name","author_test"))
                .andDo(MockMvcResultHandlers.print());
        ;
    } catch (Exception e) {
        // TODO: handle exception
        fail(e.getMessage());

    }

}
项目:Learning-Spring-5.0    文件:TestAddBookController.java   
@Test
public void testAddBook() {
    try {
        mockMVC.perform(MockMvcRequestBuilders.post("/addBook.htm")

                        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                        .param("bookName", "Book_test")
                        .param("author", "author_test")
                        .param("description", "adding book for test")
                        .param("ISBN", "1234")
                        .param("price", "9191")
                        .param("publication", "This is the test publication")
                        .requestAttr("book", new Book()))
                .andExpect(MockMvcResultMatchers.view().name("display"))
                .andExpect(MockMvcResultMatchers.model().attribute("auth_name","author_test"))
                .andDo(MockMvcResultHandlers.print());
        ;
    } catch (Exception e) {
        // TODO: handle exception
        fail(e.getMessage());

    }

}
项目:Learning-Spring-5.0    文件:TestAddBookController.java   
@Test
public void testAddBook_Form_validation() {
    try {

        mockMVC.perform(MockMvcRequestBuilders.post("/addBook.htm")

                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("bookName", "Book_test")
                .param("author", "author_test")
                .param("description", "adding book for test")
                .param("ISBN", "1234")
                .param("price", "9191")
                .param("publication", "This is the test publication")
                .requestAttr("book", new Book()))
                .andExpect(MockMvcResultMatchers.view().name("bookForm"))
                .andExpect(
                        MockMvcResultMatchers
                                .model()
                                .attributeHasErrors("book"))

                .andDo(MockMvcResultHandlers.print());
    } catch (Exception e) {
        // TODO: handle exception
        fail(e.getMessage());
        e.printStackTrace();
    }
}
项目:NGB-master    文件:ProjectControllerTest.java   
private List<ProjectVO> loadMy() throws Exception {
    ResultActions actions = mvc()
        .perform(get(URL_LOAD_MY_PROJECTS)
                     .contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_PAYLOAD).exists())
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()));
    actions.andDo(MockMvcResultHandlers.print());

    ResponseResult<List<ProjectVO>> myProjects = getObjectMapper()
        .readValue(actions.andReturn().getResponse().getContentAsByteArray(),
                   getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class,
                                                              getTypeFactory().constructParametrizedType(List.class,
                                                                                     List.class, ProjectVO.class)));

    Assert.assertNotNull(myProjects.getPayload());
    Assert.assertFalse(myProjects.getPayload().isEmpty());

    return myProjects.getPayload();
}
项目:NGB-master    文件:ProjectControllerTest.java   
private ProjectVO loadProject(long projcetId) throws Exception {
    ResultActions actions = mvc()
        .perform(get(String.format(URL_LOAD_PROJECT, projcetId)).contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_PAYLOAD).exists())
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()));
    actions.andDo(MockMvcResultHandlers.print());

    ResponseResult<ProjectVO> res = getObjectMapper()
        .readValue(actions.andReturn().getResponse().getContentAsByteArray(),
                   getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class,
                                                              ProjectVO.class));

    ProjectVO loadedProject = res.getPayload();
    Assert.assertNotNull(loadedProject);
    return loadedProject;
}
项目:NGB-master    文件:ToolsControllerTest.java   
private void assertSortRequest(FeatureFileSortRequest request, ArgumentMatcher payloadMatcher) throws Exception {
    ResultActions actions = mvc()
            .perform(post(URL_SORT).content(getObjectMapper().writeValueAsString(request))
                    .contentType(EXPECTED_CONTENT_TYPE))
            .andExpect(status().isOk())
            .andExpect(content().contentType(EXPECTED_CONTENT_TYPE))
            .andExpect(jsonPath(JPATH_PAYLOAD).value(payloadMatcher))
            .andExpect(jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()));
    actions.andDo(MockMvcResultHandlers.print());

    final ResponseResult<String> res = getObjectMapper()
            .readValue(actions.andReturn().getResponse().getContentAsByteArray(),
                    getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class,
                            String.class));

    Assert.assertNotNull(res.getPayload());
}
项目:NGB-master    文件:GeneControllerTest.java   
private void testLoadHistogram(long fileId) throws Exception {
    TrackQuery histogramQuery = initTrackQuery(fileId);
    ResultActions actions = mvc().perform(post(URL_LOAD_GENES_HISTOGRAM).content(getObjectMapper()
                                                                       .writeValueAsString(histogramQuery))
                                .contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(status().isOk())
        .andExpect(content().contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(jsonPath(JPATH_PAYLOAD).exists())
        .andExpect(jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()));
    actions.andDo(MockMvcResultHandlers.print());

    ResponseResult<Track<Wig>> histogram = getObjectMapper()
        .readValue(actions.andReturn().getResponse().getContentAsByteArray(),
                   getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class,
                                                          getTypeFactory().constructParametrizedType(Track.class,
                                                                                                     Track.class,
                                                                                                     Wig.class)));

    Assert.assertFalse(histogram.getPayload().getBlocks().isEmpty());
    Assert.assertTrue(histogram.getPayload().getBlocks()
                      .stream()
                      .allMatch(b -> b.getStartIndex() != null && b.getEndIndex() != null && b.getValue() != null));
}
项目:NGB-master    文件:FilterControllerTest.java   
@Test
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public void testSearchGenesInProject() throws Exception {
    GeneSearchQuery geneSearchQuery = new GeneSearchQuery();
    geneSearchQuery.setSearch("ENS");
    geneSearchQuery.setVcfIds(Collections.singletonList(vcfFile.getId()));

    ResultActions actions = mvc()
        .perform(post(URL_FILTER_SEARCH_GENES).content(
            getObjectMapper().writeValueAsString(geneSearchQuery)).contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_PAYLOAD).exists())
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()))
        .andDo(MockMvcResultHandlers.print());

    ResponseResult<Set<String>> geneNamesAvailable = getObjectMapper()
        .readValue(actions.andReturn().getResponse().getContentAsByteArray(),
                   getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class,
                                                              getTypeFactory().constructParametrizedType(Set.class,
                                                                                         Set.class, String.class)));

    Assert.assertFalse(geneNamesAvailable.getPayload().isEmpty());
}
项目:NGB-master    文件:FilterControllerTest.java   
@Test
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public void testGetFieldInfo() throws Exception {
    ResultActions actions = mvc()
        .perform(post(URL_FILTER_INFO).content(getObjectMapper().writeValueAsBytes(
            Collections.singletonList(vcfFile.getId()))).contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_PAYLOAD).exists())
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()));
    actions.andDo(MockMvcResultHandlers.print());

    ResponseResult<VcfFilterInfo> infoRes = getObjectMapper().readValue(
        actions.andReturn().getResponse().getContentAsByteArray(),
        getTypeFactory().constructParametrizedType(ResponseResult.class,
                                                   ResponseResult.class, VcfFilterInfo.class));

    Assert.assertNotNull(infoRes.getPayload());
    Assert.assertFalse(infoRes.getPayload().getAvailableFilters().isEmpty());
    Assert.assertNull(infoRes.getPayload().getInfoItemMap());
    Assert.assertFalse(infoRes.getPayload().getInfoItems().isEmpty());
}
项目:NGB-master    文件:FilterControllerTest.java   
@Test
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public void testGroupVariations() throws Exception {
    VcfFilterForm vcfFilterForm = new VcfFilterForm();
    vcfFilterForm.setVcfFileIds(Collections.singletonList(vcfFile.getId()));

    ResultActions actions = mvc()
        .perform(post(URL_FILTER_GROUP).content(getObjectMapper().writeValueAsString(vcfFilterForm))
                     .param("groupBy", "VARIATION_TYPE")
                     .contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_PAYLOAD).exists())
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()));
    actions.andDo(MockMvcResultHandlers.print());

    ResponseResult<List<Group>> groupRes = getObjectMapper()
        .readValue(actions.andReturn().getResponse().getContentAsByteArray(),
                   getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class,
                                      getTypeFactory().constructParametrizedType(List.class, List.class,
                                             Group.class)));

    Assert.assertFalse(groupRes.getPayload().isEmpty());
}
项目:dashboard    文件:MediaControllerMediaWebEditTest.java   
@Test
public void failedWebToUnknownMimeType() throws Exception {
    final long previousRevision = revisionService.getLatest();
    final long previousSize = mediaService.getAll().size();

    final MediaType newMediaType = MediaType.IMAGE;

    final MediaType mediaType = MediaType.IMAGE;
    final MockMultipartFile jsonFile = new MockMultipartFile("file", "texte.jpeg", "sdfsdf", "{json:null}".getBytes());

    formMediaMetadataDto.setMediaType(newMediaType.toString());

    mockMvc.perform(fileUploadAuthenticated("/media/" + formMediaMetadataDto.getUuid() + "/file")
            .file(jsonFile)
    )
            .andDo(MockMvcResultHandlers.print())
            .andExpect(status().isBadRequest())
            .andExpect(content().string(MediaController.MESSAGE_MEDIA_TYPE_NOT_SUPPORTED))
            .andReturn();

    Assert.assertEquals(previousSize, mediaService.getAll().size());
    Assert.assertEquals(previousRevision, revisionService.getLatest());
}
项目:dashboard    文件:MediaControllerMediaWebEditTest.java   
@Test
public void failedPutFileWithWrongUuid() throws Exception {
    final long previousRevision = revisionService.getLatest();
    final long previousSize = mediaService.getAll().size();

    final MediaType newMediaType = MediaType.IMAGE;

    final MediaType mediaType = MediaType.IMAGE;
    final MockMultipartFile jsonFile = new MockMultipartFile("file", "texte.jpeg", "sdfsdf", "{json:null}".getBytes());

    formMediaMetadataDto.setMediaType(newMediaType.toString());

    mockMvc.perform(fileUploadAuthenticated("/media/sdpfosdfiosd/file")
            .file(jsonFile)
    )
            .andDo(MockMvcResultHandlers.print())
            .andExpect(status().isNotFound())
            .andReturn();

    Assert.assertEquals(previousSize, mediaService.getAll().size());
    Assert.assertEquals(previousRevision, revisionService.getLatest());
}
项目:openlmis-stockmanagement    文件:StockCardTemplatesControllerIntegrationTest.java   
@Test
public void shouldGetDefaultStockCardTemplatesWithoutParams() throws Exception {
  //given
  when(stockCardTemplateService.getDefaultStockCardTemplate())
      .thenReturn(createTemplateDto());

  //when
  MockHttpServletRequestBuilder builder = get(STOCK_CARD_TEMPLATE_API)
      .param(ACCESS_TOKEN, ACCESS_TOKEN_VALUE);

  ResultActions resultActions = mvc.perform(builder);

  //then
  resultActions
      .andDo(MockMvcResultHandlers.print())
      .andExpect(status().isOk())
      .andExpect(content()
          .json("{'stockCardFields':[{'name':'packSize'}]}"));
}
项目:openlmis-stockmanagement    文件:StockCardTemplatesControllerIntegrationTest.java   
@Test
public void shouldSearchForStockCardTemplates() throws Exception {

  //given
  when(stockCardTemplateService.findByProgramIdAndFacilityTypeId(programId, facilityTypeId))
      .thenReturn(createTemplateDto());

  //when
  MockHttpServletRequestBuilder builder = get(STOCK_CARD_TEMPLATE_API)
      .param(ACCESS_TOKEN, ACCESS_TOKEN_VALUE)
      .param("program", programId.toString())
      .param("facilityType", facilityTypeId.toString());

  ResultActions resultActions = mvc.perform(builder);

  //then
  resultActions
      .andDo(MockMvcResultHandlers.print())
      .andExpect(status().isOk())
      .andExpect(content().json("{'stockCardFields':[{'name':'packSize', displayed:true}]}"));
}
项目:openlmis-stockmanagement    文件:StockEventsControllerrIntegrationTest.java   
@Test
public void shouldReturn201WhenEventSuccessfullyCreated() throws Exception {
  //given
  UUID uuid = UUID.randomUUID();
  when(stockEventProcessor.process(any(StockEventDto.class)))
      .thenReturn(uuid);

  //when
  StockEventDto stockEventDto = createStockEventDto();
  stockEventDto.getLineItems().get(0).setSourceId(null);
  stockEventDto.getLineItems().get(0).setDestinationId(null);

  ResultActions resultActions = mvc.perform(post(CREATE_STOCK_EVENT_API)
      .param(ACCESS_TOKEN, ACCESS_TOKEN_VALUE)
      .contentType(MediaType.APPLICATION_JSON)
      .content(objectToJsonString(stockEventDto)));

  //then
  resultActions.andDo(MockMvcResultHandlers.print())
      .andExpect(status().isCreated())
      .andExpect(content().string("\"" + uuid.toString() + "\""));
}
项目:site    文件:IndexControllerTest.java   
@Test
public void shouldDisplayPost() throws Exception {
    final Date postDate = Date.from(LocalDate.of(2017, 1, 1).atStartOfDay(ZoneId.systemDefault()).toInstant());
    when(this.postRepository.findByPublishedOnAndSlug(postDate, "foo")).thenReturn(Optional.of(this.posts.get(0)));
    final Optional<PostEntity> previousPost = Optional.of(this.posts.get(1));
    when(this.postRepository.getPrevious(this.posts.get(0))).thenReturn(previousPost);
    when(this.postRepository.getNext(this.posts.get(0))).thenReturn(Optional.empty());

    this.mvc.perform(
            get("/2017/1/1/foo")
    )
            .andDo(MockMvcResultHandlers.print())
            .andExpect(status().isOk())
            .andExpect(view().name("post"))
            .andExpect(model().attribute("previousPost", previousPost))
            .andExpect(model().attributeExists("post"))
            .andExpect(model().attribute("nextPost", Optional.empty()));

    verify(this.postRepository).findByPublishedOnAndSlug(postDate, "foo");
    verify(this.postRepository).getPrevious(this.posts.get(0));
    verify(this.postRepository).getNext(this.posts.get(0));
    verifyNoMoreInteractions(this.postRepository);
}
项目:NGB    文件:ProjectControllerTest.java   
private List<ProjectVO> loadMy() throws Exception {
    ResultActions actions = mvc()
        .perform(get(URL_LOAD_MY_PROJECTS)
                     .contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_PAYLOAD).exists())
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()));
    actions.andDo(MockMvcResultHandlers.print());

    ResponseResult<List<ProjectVO>> myProjects = getObjectMapper()
        .readValue(actions.andReturn().getResponse().getContentAsByteArray(),
                   getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class,
                                                              getTypeFactory().constructParametrizedType(List.class,
                                                                                     List.class, ProjectVO.class)));

    Assert.assertNotNull(myProjects.getPayload());
    Assert.assertFalse(myProjects.getPayload().isEmpty());

    return myProjects.getPayload();
}
项目:NGB    文件:ProjectControllerTest.java   
private ProjectVO loadProject(long projcetId) throws Exception {
    ResultActions actions = mvc()
        .perform(get(String.format(URL_LOAD_PROJECT, projcetId)).contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_PAYLOAD).exists())
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()));
    actions.andDo(MockMvcResultHandlers.print());

    ResponseResult<ProjectVO> res = getObjectMapper()
        .readValue(actions.andReturn().getResponse().getContentAsByteArray(),
                   getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class,
                                                              ProjectVO.class));

    ProjectVO loadedProject = res.getPayload();
    Assert.assertNotNull(loadedProject);
    return loadedProject;
}
项目:NGB    文件:ToolsControllerTest.java   
private void assertSortRequest(FeatureFileSortRequest request, ArgumentMatcher payloadMatcher) throws Exception {
    ResultActions actions = mvc()
            .perform(post(URL_SORT).content(getObjectMapper().writeValueAsString(request))
                    .contentType(EXPECTED_CONTENT_TYPE))
            .andExpect(status().isOk())
            .andExpect(content().contentType(EXPECTED_CONTENT_TYPE))
            .andExpect(jsonPath(JPATH_PAYLOAD).value(payloadMatcher))
            .andExpect(jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()));
    actions.andDo(MockMvcResultHandlers.print());

    final ResponseResult<String> res = getObjectMapper()
            .readValue(actions.andReturn().getResponse().getContentAsByteArray(),
                    getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class,
                            String.class));

    Assert.assertNotNull(res.getPayload());
}
项目:NGB    文件:GeneControllerTest.java   
private void testLoadHistogram(long fileId) throws Exception {
    TrackQuery histogramQuery = initTrackQuery(fileId);
    ResultActions actions = mvc().perform(post(URL_LOAD_GENES_HISTOGRAM).content(getObjectMapper()
                                                                       .writeValueAsString(histogramQuery))
                                .contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(status().isOk())
        .andExpect(content().contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(jsonPath(JPATH_PAYLOAD).exists())
        .andExpect(jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()));
    actions.andDo(MockMvcResultHandlers.print());

    ResponseResult<Track<Wig>> histogram = getObjectMapper()
        .readValue(actions.andReturn().getResponse().getContentAsByteArray(),
                   getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class,
                                                          getTypeFactory().constructParametrizedType(Track.class,
                                                                                                     Track.class,
                                                                                                     Wig.class)));

    Assert.assertFalse(histogram.getPayload().getBlocks().isEmpty());
    Assert.assertTrue(histogram.getPayload().getBlocks()
                      .stream()
                      .allMatch(b -> b.getStartIndex() != null && b.getEndIndex() != null && b.getValue() != null));
}
项目:NGB    文件:FilterControllerTest.java   
@Test
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public void testSearchGenesInProject() throws Exception {
    GeneSearchQuery geneSearchQuery = new GeneSearchQuery();
    geneSearchQuery.setSearch("ENS");
    geneSearchQuery.setVcfIds(Collections.singletonList(vcfFile.getId()));

    ResultActions actions = mvc()
        .perform(post(URL_FILTER_SEARCH_GENES).content(
            getObjectMapper().writeValueAsString(geneSearchQuery)).contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_PAYLOAD).exists())
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()))
        .andDo(MockMvcResultHandlers.print());

    ResponseResult<Set<String>> geneNamesAvailable = getObjectMapper()
        .readValue(actions.andReturn().getResponse().getContentAsByteArray(),
                   getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class,
                                                              getTypeFactory().constructParametrizedType(Set.class,
                                                                                         Set.class, String.class)));

    Assert.assertFalse(geneNamesAvailable.getPayload().isEmpty());
}
项目:NGB    文件:FilterControllerTest.java   
@Test
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public void testGetFieldInfo() throws Exception {
    ResultActions actions = mvc()
        .perform(post(URL_FILTER_INFO).content(getObjectMapper().writeValueAsBytes(
            Collections.singletonList(vcfFile.getId()))).contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_PAYLOAD).exists())
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()));
    actions.andDo(MockMvcResultHandlers.print());

    ResponseResult<VcfFilterInfo> infoRes = getObjectMapper().readValue(
        actions.andReturn().getResponse().getContentAsByteArray(),
        getTypeFactory().constructParametrizedType(ResponseResult.class,
                                                   ResponseResult.class, VcfFilterInfo.class));

    Assert.assertNotNull(infoRes.getPayload());
    Assert.assertFalse(infoRes.getPayload().getAvailableFilters().isEmpty());
    Assert.assertNull(infoRes.getPayload().getInfoItemMap());
    Assert.assertFalse(infoRes.getPayload().getInfoItems().isEmpty());
}
项目:NGB    文件:FilterControllerTest.java   
@Test
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public void testGroupVariations() throws Exception {
    VcfFilterForm vcfFilterForm = new VcfFilterForm();
    vcfFilterForm.setVcfFileIds(Collections.singletonList(vcfFile.getId()));

    ResultActions actions = mvc()
        .perform(post(URL_FILTER_GROUP).content(getObjectMapper().writeValueAsString(vcfFilterForm))
                     .param("groupBy", "VARIATION_TYPE")
                     .contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType(EXPECTED_CONTENT_TYPE))
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_PAYLOAD).exists())
        .andExpect(MockMvcResultMatchers.jsonPath(JPATH_STATUS).value(ResultStatus.OK.name()));
    actions.andDo(MockMvcResultHandlers.print());

    ResponseResult<List<Group>> groupRes = getObjectMapper()
        .readValue(actions.andReturn().getResponse().getContentAsByteArray(),
                   getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class,
                                      getTypeFactory().constructParametrizedType(List.class, List.class,
                                             Group.class)));

    Assert.assertFalse(groupRes.getPayload().isEmpty());
}
项目:simple-spring-restbucks    文件:SimpleRestbucksTests.java   
private String createOrder() throws Exception {

        ClassPathResource resource = new ClassPathResource("order.json");
        byte[] data = Files.readAllBytes(resource.getFile().toPath());

        // PROBLEM: "/orders" is hard-coded

        MockHttpServletResponse response = mvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON).content(data)). //
                andDo(MockMvcResultHandlers.print()). //
                andExpect(status().isCreated()). //
                andExpect(header().string("Location", is(notNullValue()))). //
                andReturn().getResponse();

        String orderResourceUrl = response.getRedirectedUrl();

        mvc.perform(get(orderResourceUrl)). //
            andDo(MockMvcResultHandlers.print()). //
            andExpect(status().isOk());

        return orderResourceUrl;
    }
项目:jandy    文件:TravisRestControllerTest.java   
@Test
  public void testPutResultsForJava() throws Exception {
//    when(travisClient.getBuild(anyLong())).thenReturn()

    MockMultipartFile multipartFile = new MockMultipartFile("samples", "java-profiler-result.jandy",
        MediaType.APPLICATION_OCTET_STREAM_VALUE, ClassLoader.getSystemResourceAsStream("java-profiler-result.jandy"));

    MockMvcBuilders.standaloneSetup(controller).build()
        .perform(MockMvcRequestBuilders.fileUpload("/rest/travis")
                .file(multipartFile)
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .param("ownerName", "jcooky")
                .param("repoName", "jandy")
                .param("buildId", "1")
                .param("branchName", "master")
                .param("buildNum", "1")
                .param("language", "java")
        )
        .andExpect(MockMvcResultMatchers.status().is2xxSuccessful())
        .andDo(MockMvcResultHandlers.print());
  }
项目:taolijie    文件:ResumeControllerTest.java   
/**
 * 修改简历 POST
 * @throws Exception
 */
@Test
public void testChangeResumePost() throws Exception {
    String expect = new JsonWrapper(true, Constants.ErrorType.SUCCESS).getAjaxMessage();
    getCredential(mem1.getId(), mem1.getUsername(), session);
    mockMvc.perform(post("/user/resume/change")
            .session(session)
            .param("id",resume1.getId().toString())
            .param("name", "小北简历12312313")
            .param("intendCategoryId", jobcate.getId().toString())
            .param("gender", "女")
            .contentType("application/json;charset=utf-8"))
            .andExpect(status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andExpect(content().json(expect))
            .andReturn();
}
项目:taolijie    文件:HomeControllerTest.java   
/**
 * 简历详情页测试(显示所有信息)
 * @throws Exception
 */
@Test
public void testResumeDetail() throws Exception{
    /*
    * 创建一个用户
    * wfc5582563 为 商家用户 role = EMPLOYER
    * */
    getCredential("wfc5582563", session);

    MvcResult result = mockMvc.perform(get("/detail/resume/"+resume1.getId())
            .session(session)
            .contentType("text/html;chrset=utf-8"))
            .andDo(MockMvcResultHandlers.print())
            .andReturn();


    Boolean isDisplay = true;
    Map<String,Object>  map= result.getModelAndView().getModel();
    for(String key:map.keySet()){
        if(key.equals("contactDisplay")){
            isDisplay = Boolean.parseBoolean(map.get(key).toString());
        }
    }
    Assert.assertTrue(isDisplay);
}
项目:taolijie    文件:SHControllerTest.java   
/**
 * 修改二手post请求
 * @throws Exception
 */
@Test
public  void testChangePost() throws Exception{
    String expect = new JsonWrapper(true, Constants.ErrorType.SUCCESS).getAjaxMessage();
    getCredential(mem1.getId(), mem1.getUsername(), session);
    System.out.println("memid:"+mem1.getId());
    mockMvc.perform(post("/user/sh/change")
            .contentType("application/json;charset=utf-8")
            .param("id", sh1.getId().toString())
            .param("title", "哈哈哈,修改成功啦")
            .param("description", "这是新的描述!!")
            .param("categoryId", shcate1.getId().toString())
            .session(session))
            .andDo(MockMvcResultHandlers.print())
            .andExpect(content().json(expect))
            .andReturn();
    List<SecondHandPostDto> list = shPostService.getAllPostList(0, 0, new ObjWrapper());
    for(SecondHandPostDto s:list){
        System.out.print("二手id: "+s.getId()+"   ");
        System.out.print("memid: " + s.getMemberId());
        System.out.println("二手标题: "+s.getTitle());
    }
}
项目:site    文件:IndexControllerTest.java   
@Test
public void shouldDisplayPost() throws Exception {
    final Date postDate = Date.from(LocalDate.of(2017, 1, 1).atStartOfDay(ZoneId.systemDefault()).toInstant());
    when(this.postRepository.findByPublishedOnAndSlug(postDate, "foo")).thenReturn(Optional.of(this.posts.get(0)));
    final Optional<PostEntity> previousPost = Optional.of(this.posts.get(1));
    when(this.postRepository.getPrevious(this.posts.get(0))).thenReturn(previousPost);
    when(this.postRepository.getNext(this.posts.get(0))).thenReturn(Optional.empty());

    this.mvc.perform(
            get("/2017/1/1/foo")
    )
            .andDo(MockMvcResultHandlers.print())
            .andExpect(status().isOk())
            .andExpect(view().name("post"))
            .andExpect(model().attribute("previousPost", previousPost))
            .andExpect(model().attributeExists("post"))
            .andExpect(model().attribute("nextPost", Optional.empty()));

    verify(this.postRepository).findByPublishedOnAndSlug(postDate, "foo");
    verify(this.postRepository).getPrevious(this.posts.get(0));
    verify(this.postRepository).getNext(this.posts.get(0));
    verifyNoMoreInteractions(this.postRepository);
}
项目:fiware-cepheus    文件:AdminControllerTest.java   
@Test
public void getStatements() throws Exception {
    List<Statement> statements = new LinkedList<>();
    Statement statement1 = new Statement("statement1", "insert into TempSensorAvg select \"OUT1\" as id, avg(temp) as avgTemp, temp_unit as avgTemp_unit from TempSensor.win:time(2 seconds) where TempSensor.id=\"S1\"");
    statements.add(statement1);
    Statement statement2 = new Statement("statement2", "ON FenceCross fc MERGE TrackerState ts WHERE fc.id = ts.id WHEN NOT MATCHED THEN INSERT SELECT id, time, location, inside WHEN MATCHED AND fc.inside != ts.inside THEN UPDATE SET inside = fc.inside");
    statements.add(statement2);
    when(complexEventProcessor.getStatements()).thenReturn(statements);

    mockMvc.perform(get("/v1/admin/statements")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andExpect(jsonPath("$.[0].name").value("statement1"))
            .andExpect(jsonPath("$.[1].name").value("statement2"));
}
项目:fiware-cepheus    文件:NgsiControllerMultiTenantTest.java   
@Test
public void postNotifyContextWithTypeNotFoundException() throws Exception {

    when(subscriptionManager.validateSubscriptionId(any(), any())).thenReturn(true);
    doThrow(TypeNotFoundException.class).when(eventMapper).eventFromContextElement(any());

    NotifyContext notifyContext = createNotifyContextTempSensor(0);

    mockMvc.perform(post("/v1/notifyContext")
            .content(json(mapper, notifyContext))
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andExpect(MockMvcResultMatchers.jsonPath("$.responseCode.code").value(CodeEnum.CODE_472.getLabel()))
            .andExpect(MockMvcResultMatchers.jsonPath("$.responseCode.reasonPhrase").value(CodeEnum.CODE_472.getShortPhrase()))
            .andExpect(MockMvcResultMatchers.jsonPath("$.responseCode.details").value("A parameter null is not valid/allowed in the request"));
}
项目:fiware-cepheus    文件:NgsiControllerMultiTenantTest.java   
@Test
public void postNotifyContextWithEventProcessingException() throws Exception {

    when(subscriptionManager.validateSubscriptionId(any(), any())).thenReturn(true);
    doThrow(EventProcessingException.class).when(eventMapper).eventFromContextElement(any());

    NotifyContext notifyContext = createNotifyContextTempSensor(0);

    mockMvc.perform(post("/v1/notifyContext")
            .content(json(mapper, notifyContext))
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andExpect(MockMvcResultMatchers.jsonPath("$.responseCode.code").value(CodeEnum.CODE_500.getLabel()))
            .andExpect(MockMvcResultMatchers.jsonPath("$.responseCode.reasonPhrase").value("event processing error"));
}
项目:fiware-cepheus    文件:NgsiControllerMultiTenantTest.java   
@Test
public void postNotifyContextWithInvalidateSubscriptionId() throws Exception {

    when(subscriptionManager.validateSubscriptionId(any(), any())).thenReturn(false);

    NotifyContext notifyContext = createNotifyContextTempSensor(0);

    mockMvc.perform(post("/v1/notifyContext")
            .content(json(mapper, notifyContext))
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andExpect(MockMvcResultMatchers.jsonPath("$.responseCode.code").value(CodeEnum.CODE_470.getLabel()))
            .andExpect(MockMvcResultMatchers.jsonPath("$.responseCode.reasonPhrase").value(CodeEnum.CODE_470.getShortPhrase()))
            .andExpect(MockMvcResultMatchers.jsonPath("$.responseCode.details").value("The subscription ID specified 1 does not correspond to an active subscription"));

}
项目:fiware-cepheus    文件:NgsiControllerMultiTenantTest.java   
@Test
public void postUpdateContextWithTypeNotExistsInConfiguration()  throws Exception {

    UpdateContext updateContext = createUpdateContextPressureSensor();
    when(eventMapper.eventFromContextElement(any())).thenReturn(event);
    doThrow(EventProcessingException.class).when(complexEventProcessor).processEvent(any());

    mockMvc.perform(post("/v1/updateContext")
            .content(json(mapper, updateContext))
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andExpect(MockMvcResultMatchers.jsonPath("$.errorCode").doesNotExist())
            .andExpect(MockMvcResultMatchers.jsonPath("$.contextResponses[0].statusCode.code").value(CodeEnum.CODE_472.getLabel()))
            .andExpect(MockMvcResultMatchers.jsonPath("$.contextResponses[0].statusCode.reasonPhrase")
                    .value(CodeEnum.CODE_472.getShortPhrase()));
}
项目:fiware-cepheus    文件:AdminControllerMultiTenantTest.java   
@Test
public void getStatements() throws Exception {
    List<Statement> statements = new LinkedList<>();
    Statement statement1 = new Statement("statement1", "insert into TempSensorAvg select \"OUT1\" as id, avg(temp) as avgTemp, temp_unit as avgTemp_unit from TempSensor.win:time(2 seconds) where TempSensor.id=\"S1\"");
    statements.add(statement1);
    Statement statement2 = new Statement("statement2", "ON FenceCross fc MERGE TrackerState ts WHERE fc.id = ts.id WHEN NOT MATCHED THEN INSERT SELECT id, time, location, inside WHEN MATCHED AND fc.inside != ts.inside THEN UPDATE SET inside = fc.inside");
    statements.add(statement2);
    when(complexEventProcessor.getStatements()).thenReturn(statements);

    mockMvc.perform(get("/v1/admin/statements")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andExpect(jsonPath("$.[0].name").value("statement1"))
            .andExpect(jsonPath("$.[1].name").value("statement2"));
}