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

项目:training_storefront    文件:VendorRepositoryControllerTests.java   
@Test
public void findAllVendorsTest(){

    List<String> vendorNames = new ArrayList<String>();

    for(VendorEntity vendorEntity : vendorEntityTestRig.getVendorEntitiesMap().values()){
        vendorNames.add(vendorEntity.getVendorName());
    }

    try {
        //http://localhost:8080/vendors/search/getVendorByVendorNameContainsIgnoreCase?vendorName=red%20hat
        mockMvc.perform(get("/vendors"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("_embedded.vendors",hasSize(vendorEntityTestRig.getVendorEntitiesMap().size())))
                .andExpect(MockMvcResultMatchers.jsonPath("_embedded.vendors[*].vendorName", containsInAnyOrder(vendorNames.toArray())))
                .andDo(print());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:nixmash-blog    文件:AdminControllerTests.java   
@Test
@WithAdminUser
public void siteSettingsUpdated_UpdatesSiteOptions() throws Exception {

    RequestBuilder request = post("/admin/site/settings")
            .param(ISiteOption.SITE_NAME, siteOptionMapDTO.getSiteName())
            .param(ISiteOption.SITE_DESCRIPTION, siteOptionMapDTO.getSiteDescription())
            .param(ISiteOption.ADD_GOOGLE_ANALYTICS, String.valueOf(siteOptionMapDTO.getAddGoogleAnalytics()))
            .param(ISiteOption.GOOGLE_ANALYTICS_TRACKING_ID, siteOptionMapDTO.getGoogleAnalyticsTrackingId())
            .param(ISiteOption.USER_REGISTRATION, String.valueOf(siteOptionMapDTO.getUserRegistration()))
            .with(csrf());

    mvc.perform(request)
            .andExpect(model().attributeHasNoErrors())
            .andExpect(MockMvcResultMatchers.flash().attributeExists("feedbackMessage"))
            .andExpect(redirectedUrl("/admin/site/settings"));
}
项目:nixmash-blog    文件:AdminPostsControllerTests.java   
@Test
public void updatePostWithValidData_RedirectsToPermalinkPage() throws Exception {

    String newTitle = "New Title for updatePostWithValidData_RedirectsToPermalinkPage Test";

    Post post = postService.getPostById(1L);
    RequestBuilder request = post("/admin/posts/update")
            .param("postId", "1")
            .param("displayType", String.valueOf(post.getDisplayType()))
            .param("postContent", post.getPostContent())
            .param("twitterCardType", post.getPostMeta().getTwitterCardType().name())
            .param("postTitle", newTitle)
            .param("tags", "updatePostWithValidData1, updatePostWithValidData2")
            .with(csrf());

    mvc.perform(request)
            .andExpect(model().hasNoErrors())
            .andExpect(MockMvcResultMatchers.flash().attributeExists("feedbackMessage"))
            .andExpect(redirectedUrl("/admin/posts"));

    Post updatedPost = postService.getPostById(1L);
    assert (updatedPost.getPostTitle().equals(newTitle));
}
项目:spring-boot-completablefuture    文件:UserControllerIntTest.java   
@Test
public void testGetUser() throws Exception {

    final MockHttpServletRequestBuilder getRequest = get(UserController.REQUEST_PATH_API_USERS +
                                                                 "/590f86d92449343841cc2c3f")
            .accept(MediaType.APPLICATION_JSON);

    final MvcResult mvcResult = mockMvc
            .perform(getRequest)
            .andExpect(MockMvcResultMatchers.request().asyncStarted())
            .andReturn();

    mockMvc
            .perform(asyncDispatch(mvcResult))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.lastName").value("One"));
}
项目:cloud-s4-sdk-examples    文件:CostCenterServiceIntegrationTest.java   
@Test
public void testHttpGet() throws Exception {
    mockSdk.requestContextExecutor().execute(new Executable() {
        @Override
        public void execute() throws Exception {
            ResultActions action = mockMvc.perform(MockMvcRequestBuilders
                    .put("/callback/tenant/" + TENANT_ID_1));
            action.andExpect(MockMvcResultMatchers.status().is2xxSuccessful());

            action = mockMvc.perform(MockMvcRequestBuilders
                    .get("/cost-center"));
            action.andExpect(MockMvcResultMatchers.status().isOk());

            action = mockMvc.perform(MockMvcRequestBuilders
                    .delete("/callback/tenant/" + TENANT_ID_1));
            action.andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
        }
    });
}
项目:cloud-s4-sdk-examples    文件:CostCenterServiceIntegrationTest.java   
@Test
public void testHttpPost() throws Exception {
    final String newCostCenterJson = buildCostCenterJson(COSTCENTER_ID_1);
    mockSdk.requestContextExecutor().execute(new Executable() {
        @Override
        public void execute() throws Exception {
            ResultActions action = mockMvc.perform(MockMvcRequestBuilders
                    .put("/callback/tenant/" + TENANT_ID_1));
            action.andExpect(MockMvcResultMatchers.status().is2xxSuccessful());

            action = mockMvc
                    .perform(MockMvcRequestBuilders
                            .request(HttpMethod.POST, "/cost-center")
                            .contentType(MediaType.APPLICATION_JSON)
                            .accept(MediaType.APPLICATION_JSON)
                            .content(newCostCenterJson));
            action.andExpect(MockMvcResultMatchers.status().isOk());

            action = mockMvc.perform(MockMvcRequestBuilders
                    .delete("/callback/tenant/" + TENANT_ID_1));
            action.andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
        }
    });
}
项目:cloud-s4-sdk-examples    文件:CostCenterServiceIntegrationTest.java   
@Test
public void testHttpAddFailure() throws Exception {
    final SapClient sapClient = mockSdk.getErpSystem().getSapClient();

    final String newCostCenterJson = getNewCostCenterAsJson(EXISTING_COSTCENTER_ID);
    // {"costcenter":"012346578","description":"demo","validFrom":...}

    // cost center already exists in database
    mockSdk.requestContextExecutor().execute(new Executable() {
        @Override
        public void execute() throws Exception {
            mockMvc
                .perform(MockMvcRequestBuilders
                    .request(HttpMethod.POST, "/api/v1/rest/client/"+sapClient+"/controllingarea/"+DEMO_CONTROLLING_AREA+"/costcenters")
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .content(newCostCenterJson))
                .andExpect(MockMvcResultMatchers
                    .status()
                    .is5xxServerError());
        }
    });
}
项目:cloud-s4-sdk-examples    文件:CostCenterServiceIntegrationTest.java   
@Test
public void testHttpAddSuccess() throws Exception {
    final SapClient sapClient = mockSdk.getErpSystem().getSapClient();

    final String newCostCenterJson = getNewCostCenterAsJson(DEMO_COSTCENTER_ID);

    final RequestBuilder newCostCenterRequest = MockMvcRequestBuilders
            .request(HttpMethod.POST, "/api/v1/rest/client/"+sapClient+"/controllingarea/"+DEMO_CONTROLLING_AREA+"/costcenters")
            .param("testRun", "true")
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)
            .content(newCostCenterJson);

    mockSdk.requestContextExecutor().execute(new Executable() {
        @Override
        public void execute() throws Exception {
            mockMvc.perform(newCostCenterRequest).andExpect(MockMvcResultMatchers.status().isOk());
        }
    });
}
项目:ItemStore    文件:ItemControllerMockMvcTest.java   
@Test
public void getItemAtALocationShouldReturnAllItemsAtThisLocation() throws Exception {

    String expectedItemDescription = "Teller";

    given(this.itemService.getItemsByLocation("Regal A"))
            .willReturn(Arrays.asList(new Item(1l,"Teller", "Regal A", LocalDate.now())));

    // Testen von JsonPath
    // http://jsonpath.com

    this.mvc.perform(get("/item/Regal A")
            .accept(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.[0].description").value(expectedItemDescription));
}
项目:ItemStore    文件:ItemControllerMockMvcTest.java   
@Test
public void getItemsAtALocationShouldReturnAllItemsAtThisLocation() throws Exception {

    String expectedItemDescription1 = "Teller";
    String expectedItemDescription2 = "Untertasse";

    given(this.itemService.getItemsByLocation("Regal A"))
            .willReturn(Arrays.asList(new Item(1l,"Teller", "Regal A", LocalDate.now()),
                    new Item(1l,"Untertasse", "Regal A", LocalDate.now())));

    // Testen von JsonPath
    // http://jsonpath.com

    this.mvc.perform(get("/item/Regal A").accept(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.[0].description").value(expectedItemDescription1))
            .andExpect(MockMvcResultMatchers.jsonPath("$.[1].description").value(expectedItemDescription2));
}
项目:ItemStore    文件:ItemControllerMockMvcTest.java   
@Test
public void updateShouldReturnTheUpdatedItemAnd200() throws Exception {
    Item item = new Item(1l,"Teller", "Regal A", null);

    given(this.itemService.update(any(Item.class))).willReturn(item);

    ObjectMapper mapper = new ObjectMapper();
    String req = mapper.writeValueAsString(item);

    this.mvc.perform(put("/item", item)
            .contentType(MediaType.APPLICATION_JSON_VALUE)
            .accept(MediaType.APPLICATION_JSON)
            .content(req))
            .andExpect(status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.location").value(item.getLocation()));
}
项目:ItemStore    文件:ItemControllerMockMvcTest.java   
@Test
public void createItem() throws Exception {
    Item item = new Item(1l,"Teller", "Regal A", null);
    ObjectMapper mapper = new ObjectMapper();
    String req = mapper.writeValueAsString(item);

    String expectedItemDescription = "Teller";
    when(itemService.create(any(Item.class))).thenReturn(item);

    this.mvc.perform(post("/item", item)
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)
            .content(req))
            .andExpect(status().isCreated())
            .andExpect(MockMvcResultMatchers.jsonPath("$.description").value(expectedItemDescription));

}
项目: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    文件: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());
}
项目:NGB-master    文件:ReferenceControllerTest.java   
@Ignore
@Test
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void testSaveAndGetTrackDataGA4GH() throws Exception {

    FileRegistrationRequest request;
    ResultActions actions;
    // 1. tries to save a genome with all parameters
    request = new FileRegistrationRequest();
    request.setPath(REFERENCE_SET_ID);
    request.setType(BiologicalDataItemResourceType.GA4GH);
    request.setName(PLAIN_GENOME_NAME);

    actions = mvc()
            .perform(post(REGISTER_GENOME_IN_FASTA_FORMAT).content(getObjectMapper().writeValueAsString(request))
                    .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()));
    final Reference ref2 = parseReference(actions.andReturn().getResponse().getContentAsByteArray()).getPayload();
    Assert.assertNotNull("Genome ID shouldn't be null.", ref2.getId());
    Assert.assertEquals("Unexpected auto-generated name for a genome.", PLAIN_GENOME_NAME, ref2.getName());
    actions.andDo(print());
}
项目:castlemock    文件:DeleteRestMockResponseControllerTest.java   
@Test
public void testDeleteMockResponse() throws Exception {
    final RestProjectDto restProjectDto = RestProjectDtoGenerator.generateRestProjectDto();
    final RestApplicationDto restApplicationDto = RestApplicationDtoGenerator.generateRestApplicationDto();
    final RestResourceDto restResourceDto = RestResourceDtoGenerator.generateRestResourceDto();
    final RestMethodDto restMethodDto = RestMethodDtoGenerator.generateRestMethodDto();
    final RestMockResponseDto restMockResponseDto = RestMockResponseDtoGenerator.generateRestMockResponseDto();
    when(serviceProcessor.process(any(ReadRestMockResponseInput.class))).thenReturn(new ReadRestMockResponseOutput(restMockResponseDto));
    final MockHttpServletRequestBuilder message = MockMvcRequestBuilders.get(SERVICE_URL + PROJECT + SLASH + restProjectDto.getId() + SLASH + APPLICATION + SLASH + restApplicationDto.getId() + SLASH + RESOURCE + SLASH + restResourceDto.getId() + SLASH + METHOD + SLASH + restMethodDto.getId() + SLASH + RESPONSE + SLASH + restMockResponseDto.getId() + SLASH + DELETE);
    mockMvc.perform(message)
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.model().size(5 + GLOBAL_VIEW_MODEL_COUNT))
            .andExpect(MockMvcResultMatchers.forwardedUrl(INDEX))
            .andExpect(MockMvcResultMatchers.model().attribute(PARTIAL, PAGE))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_PROJECT_ID, restProjectDto.getId()))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_APPLICATION_ID, restApplicationDto.getId()))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_RESOURCE_ID, restResourceDto.getId()))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_METHOD_ID, restMethodDto.getId()))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_MOCK_RESPONSE, restMockResponseDto));
}
项目:castlemock    文件:SearchControllerTest.java   
@Test
public void testCreateUser() throws Exception {
    final List<SearchResult> searchResults = new ArrayList<SearchResult>();
    final SearchResult searchResult = new SearchResult();
    searchResult.setDescription("Description");
    searchResult.setLink("Link");
    searchResult.setTitle("Title");

    final SearchCommand searchCommand = new SearchCommand();
    searchCommand.setQuery("Query");

    when(projectServiceFacade.search(any(SearchQuery.class))).thenReturn(searchResults);
    final MockHttpServletRequestBuilder message = MockMvcRequestBuilders.post(SERVICE_URL, searchCommand);
    mockMvc.perform(message)
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.model().size(1 + GLOBAL_VIEW_MODEL_COUNT))
            .andExpect(MockMvcResultMatchers.forwardedUrl(INDEX))
            .andExpect(MockMvcResultMatchers.model().attribute(PARTIAL, PAGE))
            .andExpect(MockMvcResultMatchers.model().attribute(SEARCH_RESULTS, searchResults));
}
项目:castlemock    文件:RestResourceControllerTest.java   
@Test
public void testGetServiceValid() throws Exception {
    final RestProjectDto restProjectDto = RestProjectDtoGenerator.generateRestProjectDto();
    final RestApplicationDto restApplicationDto = RestApplicationDtoGenerator.generateRestApplicationDto();
    final RestResourceDto restResourceDto = RestResourceDtoGenerator.generateRestResourceDto();
    when(serviceProcessor.process(isA(ReadRestResourceInput.class))).thenReturn(new ReadRestResourceOutput(restResourceDto));
    final MockHttpServletRequestBuilder message = MockMvcRequestBuilders.get(SERVICE_URL + PROJECT + SLASH + restProjectDto.getId() + SLASH + APPLICATION + SLASH + restApplicationDto.getId() + SLASH + RESOURCE + SLASH + restResourceDto.getId());
    ResultActions result = mockMvc.perform(message)
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.model().size(5 + GLOBAL_VIEW_MODEL_COUNT))
            .andExpect(MockMvcResultMatchers.forwardedUrl(INDEX))
            .andExpect(MockMvcResultMatchers.model().attribute(PARTIAL, PAGE))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_PROJECT_ID, restProjectDto.getId()))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_APPLICATION_ID, restApplicationDto.getId()))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_RESOURCE, restResourceDto));
    RestResourceDto restResourceDtoResponse = (RestResourceDto) result.andReturn().getModelAndView().getModel().get(REST_RESOURCE);
    String hostAddress = restResourceController.getHostAddress();
}
项目:castlemock    文件:UpdateCurrentUserControllerTest.java   
@Test
public void testUpdate() throws Exception {
    final UserDto userDto = UserDtoGenerator.generateUserDto();

    final UpdateCurrentUserOutput updateCurrentUserOutput = new UpdateCurrentUserOutput(userDto);
    when(serviceProcessor.process(any(UpdateCurrentUserInput.class))).thenReturn(updateCurrentUserOutput);


    final UpdateCurrentUserCommand updateCurrentUserCommand = new UpdateCurrentUserCommand();
    updateCurrentUserCommand.setUser(userDto);
    final MockHttpServletRequestBuilder message = MockMvcRequestBuilders.post(SERVICE_URL, updateCurrentUserCommand);

    mockMvc.perform(message)
            .andExpect(MockMvcResultMatchers.status().isFound())
            .andExpect(MockMvcResultMatchers.model().size(1));
}
项目: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;
}
项目:castlemock    文件:SoapAddWSDLControllerTest.java   
@Test
public void testAddWSDLPostLink() throws Exception {
    final SoapProjectDto soapProjectDto = SoapProjectDtoGenerator.generateSoapProjectDto();
    final List<File> files = new ArrayList<>();
    final WSDLFileUploadForm uploadForm = new WSDLFileUploadForm();
    final List<MultipartFile> uploadedFiles = new ArrayList<>();
    uploadForm.setFiles(uploadedFiles);


    when(serviceProcessor.process(any(ReadSoapProjectInput.class))).thenReturn(new ReadSoapProjectOutput(soapProjectDto));
    when(fileManager.uploadFiles(anyString())).thenReturn(files);
    final MockHttpServletRequestBuilder message = MockMvcRequestBuilders.post(SERVICE_URL + SLASH + PROJECT + SLASH + soapProjectDto.getId() + SLASH + ADD + SLASH + WSDL).param("type", "link").requestAttr("uploadForm", uploadForm);
    mockMvc.perform(message)
            .andExpect(MockMvcResultMatchers.status().isFound())
            .andExpect(MockMvcResultMatchers.model().size(1));
    Mockito.verify(fileManager, times(1)).uploadFiles(anyString());
}
项目:castlemock    文件:RestMockResponseControllerTest.java   
@Test
public void testGetMockResponse() throws Exception {
    final RestProjectDto restProjectDto = RestProjectDtoGenerator.generateRestProjectDto();
    final RestApplicationDto restApplicationDto = RestApplicationDtoGenerator.generateRestApplicationDto();
    final RestResourceDto restResourceDto = RestResourceDtoGenerator.generateRestResourceDto();
    final RestMethodDto restMethodDto = RestMethodDtoGenerator.generateRestMethodDto();
    final RestMockResponseDto restMockResponseDto = RestMockResponseDtoGenerator.generateRestMockResponseDto();
    when(serviceProcessor.process(any(ReadRestMockResponseInput.class))).thenReturn(new ReadRestMockResponseOutput(restMockResponseDto));
    final MockHttpServletRequestBuilder message = MockMvcRequestBuilders.get(SERVICE_URL + PROJECT + SLASH + restProjectDto.getId() + SLASH + APPLICATION + SLASH + restApplicationDto.getId() + SLASH + RESOURCE + SLASH + restResourceDto.getId() + SLASH + METHOD + SLASH + restMethodDto.getId() + SLASH + RESPONSE + SLASH + restMockResponseDto.getId());
    mockMvc.perform(message)
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.model().size(6 + GLOBAL_VIEW_MODEL_COUNT))
            .andExpect(MockMvcResultMatchers.forwardedUrl(INDEX))
            .andExpect(MockMvcResultMatchers.model().attribute(PARTIAL, PAGE))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_PROJECT_ID, restProjectDto.getId()))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_APPLICATION_ID, restApplicationDto.getId()))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_RESOURCE_ID, restResourceDto.getId()))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_METHOD_ID, restMethodDto.getId()))
            .andExpect(MockMvcResultMatchers.model().attribute(DEMO_MODE, false))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_MOCK_RESPONSE, restMockResponseDto));
}
项目:unity    文件:UserControllerIT.java   
@Test
public void getAllUsers_Success() throws Exception {
    mvc.perform(MockMvcRequestBuilders.request(HttpMethod.GET, "/api/v1/user")
            .accept(contentType)
            .contentType(contentType)
            .header(authHeaderName, token))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$[0].id", is(user.getId())))
            .andExpect(MockMvcResultMatchers.jsonPath("$[0].username", is(user.getUsername())))
            .andExpect(MockMvcResultMatchers.jsonPath("$[0].password", is(user.getPassword())))
            .andExpect(MockMvcResultMatchers.jsonPath("$[0].createdAt", is(user.getCreatedAt().getTime())))
            .andExpect(MockMvcResultMatchers.jsonPath("$[0].updatedAt", is(user.getUpdatedAt().getTime())))
            .andExpect(MockMvcResultMatchers.jsonPath("$[0].authorities", is(user.getAuthorities()
                    .stream()
                    .map(Authority::getAuthority)
                    .collect(Collectors.toList()))));
}
项目:castlemock    文件:DeleteSoapMockResponseControllerTest.java   
@Test
public void testConfirmDeletationOfMultipleMockResponses() throws Exception {
    final SoapProjectDto projectDto = SoapProjectDtoGenerator.generateSoapProjectDto();
    final SoapPortDto applicationDto = SoapPortDtoGenerator.generateSoapPortDto();
    final SoapOperationDto soapOperationDto = SoapOperationDtoGenerator.generateSoapOperationDto();
    final SoapMockResponseDto soapMockResponseDto = SoapMockResponseDtoGenerator.generateSoapMockResponseDto();
    final DeleteSoapMockResponsesCommand deleteSoapMockResponsesCommand = new DeleteSoapMockResponsesCommand();
    deleteSoapMockResponsesCommand.setSoapMockResponses(new ArrayList<SoapMockResponseDto>());
    deleteSoapMockResponsesCommand.getSoapMockResponses().add(soapMockResponseDto);

    when(serviceProcessor.process(any(DeleteSoapMockResponseInput.class))).thenReturn(new DeleteSoapMockResponseOutput());
    final MockHttpServletRequestBuilder message = MockMvcRequestBuilders.post(SERVICE_URL + PROJECT + SLASH + projectDto.getId() + SLASH + PORT + SLASH + applicationDto.getId() + SLASH + OPERATION + SLASH + soapOperationDto.getId() + SLASH + RESPONSE + SLASH + DELETE + SLASH + CONFIRM);
    mockMvc.perform(message)
            .andExpect(MockMvcResultMatchers.status().isFound())
            .andExpect(MockMvcResultMatchers.model().size(1));
}
项目:castlemock    文件:UpdateRestMethodControllerTest.java   
@Test
public void testUpdateMethod() throws Exception {
    final RestProjectDto restProjectDto = RestProjectDtoGenerator.generateRestProjectDto();
    final RestApplicationDto restApplicationDto = RestApplicationDtoGenerator.generateRestApplicationDto();
    final RestResourceDto restResourceDto = RestResourceDtoGenerator.generateRestResourceDto();
    final RestMethodDto restMethodDto = RestMethodDtoGenerator.generateRestMethodDto();
    when(serviceProcessor.process(any(ReadRestMethodInput.class))).thenReturn(new ReadRestMethodOutput(restMethodDto));
    final MockHttpServletRequestBuilder message = MockMvcRequestBuilders.get(SERVICE_URL + PROJECT + SLASH + restProjectDto.getId() + SLASH + APPLICATION + SLASH + restApplicationDto.getId() + SLASH + RESOURCE + SLASH + restResourceDto.getId() + SLASH + METHOD + SLASH + restMethodDto.getId() + SLASH + UPDATE);
    mockMvc.perform(message)
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.model().size(8 + GLOBAL_VIEW_MODEL_COUNT))
            .andExpect(MockMvcResultMatchers.forwardedUrl(INDEX))
            .andExpect(MockMvcResultMatchers.model().attribute(PARTIAL, PAGE))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_PROJECT_ID, restProjectDto.getId()))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_APPLICATION_ID, restApplicationDto.getId()))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_RESOURCE_ID, restResourceDto.getId()))
            .andExpect(MockMvcResultMatchers.model().attribute(REST_METHOD, restMethodDto));
}
项目:castlemock    文件:UpdateSoapPortControllerTest.java   
@Test
public void testUpdatePortEndpoint() throws Exception {
    final UpdateSoapPortsEndpointCommand command = new UpdateSoapPortsEndpointCommand();
    final SoapProjectDto soapProjectDto = SoapProjectDtoGenerator.generateSoapProjectDto();
    final SoapPortDto soapPortDto = SoapPortDtoGenerator.generateSoapPortDto();
    final List<SoapPortDto> soapPorts = new ArrayList<SoapPortDto>();
    soapPorts.add(soapPortDto);
    command.setSoapPorts(soapPorts);
    command.setForwardedEndpoint("/new/endpoint");

    when(serviceProcessor.process(any(Input.class))).thenReturn(new UpdateSoapPortOutput(soapPortDto));
    final MockHttpServletRequestBuilder message = MockMvcRequestBuilders.post(SERVICE_URL + PROJECT + SLASH + soapProjectDto.getId() + SLASH + PORT +  SLASH + UPDATE + SLASH + CONFIRM, command);
    mockMvc.perform(message)
            .andExpect(MockMvcResultMatchers.status().isFound())
            .andExpect(MockMvcResultMatchers.model().size(1));
}
项目:unity    文件:UserAnalyticsControllerIT.java   
@Test
public void getAnalyticsByUserId_Success_IfAnalyticsAndUserPresent() throws Exception {
    mvc.perform(MockMvcRequestBuilders.request(HttpMethod.GET, "/api/v1/user/" + user.getId() + "/analytics")
            .accept(contentType)
            .contentType(contentType)
            .header(authHeaderName, token))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.id", is(analytics.getId())))
            .andExpect(MockMvcResultMatchers.jsonPath("$.userId", is(analytics.getUserId())))
            .andExpect(MockMvcResultMatchers.jsonPath("$.createdAt", is(analytics.getCreatedAt().getTime())))
            .andExpect(MockMvcResultMatchers.jsonPath("$.updatedAt", is(analytics.getUpdatedAt().getTime())))
            .andExpect(MockMvcResultMatchers.jsonPath("$.reports[0].result", is(analytics.getReports().get(0).getResult())))
            .andExpect(MockMvcResultMatchers.jsonPath("$.reports[0].id", is(analytics.getReports().get(0).getId())))
            .andExpect(MockMvcResultMatchers.jsonPath("$.reports[0].resource", is(analytics.getReports().get(0).getResource().toString())))
            .andExpect(MockMvcResultMatchers.jsonPath("$.reports[0].analyzedAt", is(analytics.getReports().get(0).getAnalyzedAt().getTime())))
            .andExpect(MockMvcResultMatchers.jsonPath("$.reports[0].analysisTime", is(analytics.getReports().get(0).getAnalysisTime().intValue())));
}
项目:castlemock    文件:ProjectOverviewControllerTest.java   
@Test
public void testGetServiceValid() throws Exception {
    final List<ProjectDto> projectDtos = new ArrayList<ProjectDto>();
    for(int index = 0; index < MAX_PROJECT_COUNT; index++){
        final ProjectDto projectDto = ProjectDtoGenerator.generateProjectDto();
        projectDtos.add(projectDto);
    }

    when(projectServiceComponent.findAll()).thenReturn(projectDtos);
    final MockHttpServletRequestBuilder message = MockMvcRequestBuilders.get(SERVICE_URL);
    mockMvc.perform(message)
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.model().size(2 + GLOBAL_VIEW_MODEL_COUNT))
            .andExpect(MockMvcResultMatchers.forwardedUrl(INDEX))
            .andExpect(MockMvcResultMatchers.model().attribute(PARTIAL, PAGE))
            .andExpect(MockMvcResultMatchers.model().attribute(PROJECTS, projectDtos));
}
项目:castlemock    文件:RestImportDefinitionControllerTest.java   
@Test
public void testImportPostFile() throws Exception {
    final RestProjectDto restProjectDto = RestProjectDtoGenerator.generateRestProjectDto();
    final List<File> files = new ArrayList<File>();
    final RestDefinitionFileUploadForm uploadForm = new RestDefinitionFileUploadForm();
    final List<MultipartFile> uploadedFiles = new ArrayList<>();
    uploadForm.setFiles(uploadedFiles);

    when(serviceProcessor.process(any(ReadRestProjectInput.class))).thenReturn(new ReadRestProjectOutput(restProjectDto));
    when(fileManager.uploadFiles(anyListOf(MultipartFile.class))).thenReturn(files);
    final MockHttpServletRequestBuilder message = MockMvcRequestBuilders.post(SERVICE_URL + SLASH + PROJECT + SLASH + restProjectDto.getId() + SLASH + IMPORT).param(TYPE_PARAMETER, FILE).requestAttr("uploadForm", uploadForm);
    mockMvc.perform(message)
            .andExpect(MockMvcResultMatchers.status().isFound())
            .andExpect(MockMvcResultMatchers.model().size(1));
    Mockito.verify(fileManager, times(1)).uploadFiles(anyListOf(MultipartFile.class));
}
项目:castlemock    文件:SoapPortControllerTest.java   
@Test
public void getSoapPort() throws Exception {
    final SoapProjectDto soapProjectDto = SoapProjectDtoGenerator.generateSoapProjectDto();
    final SoapPortDto soapPortDto = SoapPortDtoGenerator.generateSoapPortDto();
    final SoapOperationDto soapOperationDto = SoapOperationDtoGenerator.generateSoapOperationDto();
    final List<SoapOperationDto> operationDtos = new ArrayList<SoapOperationDto>();
    operationDtos.add(soapOperationDto);
    soapPortDto.setOperations(operationDtos);
    when(serviceProcessor.process(any(ReadSoapPortInput.class))).thenReturn(new ReadSoapPortOutput(soapPortDto));
    final MockHttpServletRequestBuilder message = MockMvcRequestBuilders.get(SERVICE_URL + PROJECT + SLASH + soapProjectDto.getId() + SLASH + PORT + SLASH + soapPortDto.getId() + SLASH);
    ResultActions result = mockMvc.perform(message)
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.model().size(4 + GLOBAL_VIEW_MODEL_COUNT))
            .andExpect(MockMvcResultMatchers.forwardedUrl(INDEX))
            .andExpect(MockMvcResultMatchers.model().attribute(PARTIAL, PAGE))
            .andExpect(MockMvcResultMatchers.model().attribute(SOAP_PORT, soapPortDto));
    SoapPortDto soapPortDtoResponse = (SoapPortDto) result.andReturn().getModelAndView().getModel().get(SOAP_PORT);
}
项目:cdct    文件:CustomerServiceRestdocsApplicationTests.java   
@Test
public void getCustomerByIdShouldReturnCustomer() throws Exception {

    Mockito
            .when(this.customerRepository.findOne(1L))
            .thenReturn(c1);

    mockMvc.perform(MockMvcRequestBuilders.get("/customers/1"))
            .andExpect(MockMvcResultMatchers.status().is2xxSuccessful())
            .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(MockMvcResultMatchers.jsonPath("@.id").value(1L))
            .andDo(MockMvcRestDocumentation.document("customerById"));
}