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

项目:theskeleton    文件:PrivilegeRestControllerTest.java   
@Test
public void testFindPrivilegeByName() throws Exception {
    PrivilegeEntity dbResult = new PrivilegeEntity()
            .setId("123")
            .setName("12345")
            .setDescription("Description 12345");
    when(privilegeService.findPrivilegeByIdOrName("123")).thenReturn(dbResult);
    ResultActions resultActions = mockMvc.perform(get("/api/privileges/123").contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(document("privilege-read"));
    MockHttpServletResponse response = resultActions
            .andReturn()
            .getResponse();
    verify(privilegeService).findPrivilegeByIdOrName("123");
    assertThat(response.getContentAsByteArray())
            .isEqualTo(objectMapper.writeValueAsBytes(PrivilegeRestData.builder().fromPrivilegeEntity(dbResult).build()));
}
项目:csap-core    文件:Landing_Page.java   
@Test
public void http_get_hello_endpoint() throws Exception {
    logger.info(Boot_Container_Test.TC_HEAD + "simple mvc test" );
    // mock does much validation.....
    ResultActions resultActions = mockMvc.perform(
            get( "/hello" )
                    .accept( MediaType.TEXT_PLAIN ) );

    //
    String result = resultActions
            .andExpect( status().isOk() )
            .andExpect( content().contentType( "text/plain;charset=UTF-8" ) )
            .andReturn().getResponse().getContentAsString();
    logger.info( "result:\n" + result );

    assertThat( result )
            .startsWith( "Hello") ;
}
项目:keti    文件:SubjectPrivilegeManagementControllerIT.java   
@Test
public void subjectZoneDoesNotExistException() throws Exception {
    // NOTE: To throw a ZoneDoesNotExistException, we must ensure that the AcsRequestContext in the
    //       SpringSecurityZoneResolver class returns a null ZoneEntity
    MockSecurityContext.mockSecurityContext(null);
    MockAcsRequestContext.mockAcsRequestContext();

    BaseSubject subject = JSON_UTILS.deserializeFromFile("controller-test/a-subject.json", BaseSubject.class);
    MockMvcContext putContext = TEST_UTILS.createWACWithCustomPUTRequestBuilder(this.wac,
            "zoneDoesNotExist", SUBJECT_BASE_URL + '/' + subject.getSubjectIdentifier());
    ResultActions resultActions = putContext.getMockMvc().perform(putContext.getBuilder()
            .contentType(MediaType.APPLICATION_JSON).content(OBJECT_MAPPER.writeValueAsString(subject)));
    resultActions.andExpect(status().isBadRequest());
    resultActions.andReturn().getResponse().getContentAsString().contentEquals("Zone not found");
    MockSecurityContext.mockSecurityContext(this.testZone);
    MockAcsRequestContext.mockAcsRequestContext();
}
项目:theskeleton    文件:RoleRestControllerTest.java   
@Test
public void testFindRoles() throws Exception {
    RoleEntity dbResult = new RoleEntity()
            .setId("123")
            .setCode("12345")
            .setDescription("Description 12345");
    Page<RoleEntity> pageResponseBody = new PageImpl<>(Arrays.asList(dbResult));
    Page<RoleRestData> expectedResponseBody = new PageImpl<>(Arrays.asList(RoleRestData.builder()
            .fromRoleEntity(dbResult).build()));
    when(roleService.findRoles(anyString(), any())).thenReturn(pageResponseBody);
    ResultActions resultActions = mockMvc.perform(get("/api/roles")
                .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(document("role-read-all"));
    MockHttpServletResponse response = resultActions
            .andReturn()
            .getResponse();
    verify(roleService).findRoles(anyString(), any());
    assertThat(response.getContentAsByteArray()).isEqualTo(objectMapper.writeValueAsBytes(expectedResponseBody));
}
项目: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));
}
项目:keti    文件:PolicyManagementControllerIT.java   
public void policyZoneDoesNotExistException() throws Exception {
    // NOTE: To throw a ZoneDoesNotExistException, we must ensure that the AcsRequestContext in the
    //       SpringSecurityZoneResolver class returns a null ZoneEntity
    MockSecurityContext.mockSecurityContext(null);
    MockAcsRequestContext.mockAcsRequestContext();
    String thisUri = VERSION + "/policy-set/" + this.policySet.getName();
    // create policy-set in first zone
    MockMvcContext putContext = this.testUtils.createWACWithCustomPUTRequestBuilder(this.wac,
            this.testZone.getSubdomain(), thisUri);
    ResultActions resultActions = putContext.getMockMvc().perform(
            putContext.getBuilder().contentType(MediaType.APPLICATION_JSON)
                    .content(this.objectWriter.writeValueAsString(this.policySet)));
    resultActions.andExpect(status().isUnprocessableEntity());
    resultActions.andReturn().getResponse().getContentAsString().contains("zone 'null' does not exist");

    MockSecurityContext.mockSecurityContext(this.testZone);
    MockAcsRequestContext.mockAcsRequestContext();
}
项目:springrestdoc    文件:SpeakerControllerTest.java   
@Test
public void testCreateSpeaker_conflict() throws Exception {
    //Given
    Speaker josh = given.speaker("Josh Long").company("Pivotal").save();
    String requestBody = given.asJsonString(given.speakerDto("Josh Long").company("Pivotal").build());

    //When
    ResultActions action = mockMvc.perform(post("/speakers").content(requestBody));
    action.andDo(print());

    //Then
    assertEquals(1, speakerRepository.count());
    action.andExpect(status().isConflict());
    action.andExpect(jsonPath("content", is("Entity  Speaker with name 'Josh Long' already present in DB.")));
    action.andDo(document("{class-name}/{method-name}",
            responseFields(
                    fieldWithPath("content").description("Errors that were found during validation."))));
}
项目: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();
}
项目:theskeleton    文件:RoleRestControllerTest.java   
@Test
public void testUpdateRole() throws Exception {
    RoleEntity input = new RoleEntity()
            .setId("123")
            .setCode("12345")
            .setDescription("Description 12345");
    RoleEntity dbResult = new RoleEntity()
            .setId(UUID.randomUUID().toString())
            .setCode("12345")
            .setDescription("Description 12345");
    byte[] jsonInput = objectMapper.writeValueAsBytes(RoleRestData.builder().fromRoleEntity(input).build());
    when(roleService.updateRole(eq("123"), any())).thenReturn(dbResult);
    ResultActions resultActions = mockMvc.perform(put("/api/roles/123")
                .contentType(MediaType.APPLICATION_JSON)
                .content(jsonInput))
            .andExpect(status().isOk())
            .andDo(document("role-update"));
    MockHttpServletResponse response = resultActions
            .andReturn()
            .getResponse();
    verify(roleService).updateRole(eq("123"), any());
    assertThat(response.getContentAsByteArray())
            .isEqualTo(objectMapper.writeValueAsBytes(RoleRestData.builder().fromRoleEntity(dbResult).build()));
}
项目:theskeleton    文件:UserRestControllerTest.java   
@Test
public void testEnableOrDisableUser() throws Exception {
    final UserEntity user = new UserEntity()
            .setEnabled(true);
    when(userAdminService.enableOrDisableUser("user123", true)).thenReturn(user);
    ResultActions resultActions = mockMvc.perform(put("/api/users/user123/enable")
                .content("{\"enabled\": true}")
                .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(document("user-enable"));
    MockHttpServletResponse response = resultActions
            .andReturn()
            .getResponse();
    assertThat(response.getContentAsByteArray())
            .isEqualTo(objectMapper.writeValueAsBytes(UserRestData.builder().fromUserEntity(user).build()));
    verify(userAdminService).enableOrDisableUser("user123", true);
}
项目:Spring-Boot-Examples    文件:TodoControllerTest.java   
@Test
public void shouldPartialUpdateTodo() throws Exception {
    // Given
    Todo todo = new Todo(1L, "title", "desc");
    given(todoService.getTodoById(1L)).willReturn(todo);
    HashMap<String, Object> updates = new HashMap<>();
    updates.put("title", "new title");
    updates.put("description", "new description");
    // When
    ResultActions result = this.mvc.perform(patch("/todos/1")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .content(objectMapper.writeValueAsString(updates)));
    // Then
    result.andExpect(status().isNoContent())
            .andExpect(status().reason("Todo partial updated!"));
}
项目:theskeleton    文件:UserRestControllerTest.java   
@Test
public void testUpdateUserPassword() throws Exception {
    final UserEntity user = new UserEntity()
            .setId("user123");
    when(userAdminService.updateUserPassword(eq("user123"), any())).thenReturn(user);
    ResultActions resultActions = mockMvc.perform(put("/api/users/user123/password")
                .content("{\"username\": \"user123\"}")
                .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(document("user-update-password"));
    MockHttpServletResponse response = resultActions
            .andReturn()
            .getResponse();
    assertThat(response.getContentAsByteArray())
            .isEqualTo(objectMapper.writeValueAsBytes(UserRestData.builder().fromUserEntity(user).build()));
    verify(userAdminService).updateUserPassword(eq("user123"), any());
}
项目:theskeleton    文件:RoleRestControllerTest.java   
@Test
public void testRemovePrivilegeFromRole() throws Exception {
    final RoleEntity role = new RoleEntity()
            .setId("role123")
            .setCode("role123");
    when(roleService.removePrivilegeFromRole("role123", "privilege123")).thenReturn(role);
    ResultActions resultActions = mockMvc.perform(delete("/api/roles/role123/privileges")
                .content("{\"privilege\": \"privilege123\"}")
                .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(document("role-privilege-delete"));
    MockHttpServletResponse response = resultActions
            .andReturn()
            .getResponse();
    verify(roleService).removePrivilegeFromRole("role123", "privilege123");
    assertThat(response.getContentAsByteArray())
            .isEqualTo(objectMapper.writeValueAsBytes(RoleRestData.builder().fromRoleEntity(role).build()));
}
项目: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());
}
项目:devops-cstack    文件:AbstractApplicationControllerTestIT.java   
@Test(timeout = 60000)
public void test_changeJvmOptionsApplicationTest()
        throws Exception {

    createApplication(applicationName);

    logger.info("Change JVM Options !");
    String jsonString =
            "{\"applicationName\":\"" + applicationName
                   + "\",\"jvmMemory\":\"512\",\"jvmOptions\":\"-Dkey1=value1\"}";
    ResultActions resultats =
            mockMvc.perform(put("/server/configuration/jvm").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString));
    resultats.andExpect(status().isOk());

    resultats =
            mockMvc.perform(get("/application/" + applicationName).session(session).contentType(MediaType.APPLICATION_JSON));
    resultats.andExpect(jsonPath("$.server.jvmMemory").value(512))
            .andExpect(jsonPath("$.server.jvmOptions").value("-Dkey1=value1"));

    deleteApplication(applicationName);
}
项目:projectindoorweb    文件:EverythingControllerTest.java   
private long processRadioMapForBuilding(long buildingId) throws Exception {

        mockMvc.perform(MockMvcRequestBuilders.fileUpload("/position/processRadioMapFiles")
                .file(radioMapFileR01A5)
                .param("buildingIdentifier", String.valueOf(buildingId)))
                .andExpect(status().isOk());

        ResultActions getRadioMapResultActions = mockMvc.perform(get("/position/getRadioMapsForBuildingId?" +
                "buildingIdentifier=" + buildingId));
        getRadioMapResultActions.andExpect(status().isOk());

        String getRadioMapResult = getRadioMapResultActions.andReturn().getResponse().getContentAsString();
        List<GetRadioMapFilesForBuilding> getRadioMapFilesForBuilding = (List<GetRadioMapFilesForBuilding>)
                this.objectMapper.readValue(getRadioMapResult, new TypeReference<List<GetRadioMapFilesForBuilding>>() {
                });
        assertTrue("The returned list of type " + GetRadioMapFilesForBuilding.class.getSimpleName() + " had an unexpected size.",
                getRadioMapFilesForBuilding.size() == 1);

        return getRadioMapFilesForBuilding.get(0).getId();

    }
项目:document-management-store-app    文件:RestActions.java   
public ResultActions postDocumentVersion(String urlTemplate, MockMultipartFile file) {

        MockMultipartHttpServletRequestBuilder builder =
                MockMvcRequestBuilders.fileUpload(urlTemplate);


        builder.with(request -> {
            request.setMethod("POST");
            return request;
        });

        return translateException(() -> mvc.perform(
                builder
                    .file(file)
                    .headers(httpHeaders)
        ));

    }
项目:devops-cstack    文件:Apache2ControllerTestIT.java   
@Before
public void createApplication() {
    try {
        final String jsonString =
                "{\"applicationName\":\"" + applicationName + "\", \"serverName\":\"" + release + "\"}";
        ResultActions resultats =
                mockMvc.perform(post("/application").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString));
        resultats.andExpect(status().isOk());

        resultats =
                mockMvc.perform(get("/application/" + applicationName).session(session).contentType(MediaType.APPLICATION_JSON));
        resultats.andExpect(jsonPath("name").value(applicationName.toLowerCase()));
    } catch (Exception e) {
        logger.error(e.getLocalizedMessage());
    }
}
项目:devops-cstack    文件:VolumeControllerTestIT.java   
/**
* Cannot create two volumes with same name
*
* @throws Exception
*/
@Test()
public void createTwoVolumesWithError()
        throws Exception {
    VolumeResource volumeResource = new VolumeResource();

    volumeResource.setName("shared" + new Random().nextInt(100000));
    ResultActions resultActions = createVolume(volumeResource);
    resultActions.andExpect(status().isCreated());
    // Convert the result to pojo
    volumeResource = getVolumeResource(mapper, resultActions);

    // Try to create a second volume but error
    resultActions = createVolume(volumeResource);
    resultActions.andExpect(status().is4xxClientError());

    // delete the volume
    deleteVolume(volumeResource.getId(), HttpStatus.NO_CONTENT);
}
项目:bruxelas    文件:TalkerRestControllerTest.java   
@Test
public void testSaveTalker() throws Exception{
    String talkerAsJson = this.mapper.writeValueAsString(this.talkerAny);

    when(this.talkerServiceMock.save(this.talkerAny)).thenReturn(this.talkerAny);

    ResultActions resultActions = mockMvc.perform(post("/api/talker")
            .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
            .content(talkerAsJson))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));

    assertNotNull("[resultActions] should not be null", resultActions);

    MockHttpServletResponse response = resultActions.andReturn().getResponse();
    assertNotNull("[ContentAsString] should not be null", response.getContentAsString());

    Talker talkerFromJson = this.mapper.readValue(response.getContentAsString(), Talker.class);
    assertEquals("[talkerFromJson] should be equals to [talkerAny]", this.talkerAny, talkerFromJson);

    verify(this.talkerServiceMock, times(1)).save(this.talkerAny);
}
项目:springrestdoc    文件:SpeakerControllerTest.java   
@Test
public void testGetAllSpeakers() throws Exception {
    //Given
    Speaker josh = given.speaker("Josh Long").company("Pivotal").save();
    Speaker venkat = given.speaker("Venkat Subramaniam").company("Agile").save();

    //When
    ResultActions action = mockMvc.perform(
            get("/speakers").accept(MediaTypes.HAL_JSON));

    //Then
    action.andDo(print()).andExpect(status().isOk());
    action.andDo(document("{class-name}/{method-name}",
            responseFields(
                    fieldWithPath("_embedded").description("'speakers' array with Speakers resources."),
                    fieldWithPath("_embedded.speakers").description("Array with returned Speaker resources."),
                    fieldWithPath("_embedded.speakers[].name").description("Speaker's name."),
                    fieldWithPath("_embedded.speakers[].company").description("Speaker's company."),
                    fieldWithPath("_embedded.speakers[].status").description("Speaker's status name."),
                    fieldWithPath("_embedded.speakers[]._links").description("Link section."),
                    subsectionWithPath("_embedded.speakers[]._links").description("<<resources-tags-links, " +
                            "HATEOAS Links>> to Speaker actions")
            )

    ));
}
项目:devops-cstack    文件:AbstractApplicationControllerTestIT.java   
@Test()
public void test_openAPort()
        throws Exception {
    createApplication(applicationName);
    logger.info("Open custom ports !");
    String jsonString =
            "{\"applicationName\":\"" + applicationName
                    + "\",\"portToOpen\":\"6115\",\"alias\":\"access6115\"}";
    ResultActions resultats =
            this.mockMvc.perform(post("/server/ports/open").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString));
    resultats.andExpect(status().isOk());
    logger.info("Close custom ports !");
    jsonString =
            "{\"applicationName\":\"" + applicationName
                    + "\",\"portToOpen\":\"6115\",\"alias\":\"access6115\"}";
    resultats =
            this.mockMvc.perform(post("/server/ports/close").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString));
    resultats.andExpect(status().isOk());
    deleteApplication(applicationName);
}
项目:theskeleton    文件:UserRestControllerTest.java   
@Test
public void testAddRoleToUser() throws Exception {
    final UserEntity user = new UserEntity()
            .setId("123")
            .setUsername("user123")
            .setPassword("123456");
    when(userAdminService.addRoleToUser("user123", "role123")).thenReturn(user);
    ResultActions resultActions = mockMvc.perform(put("/api/users/user123/roles")
                .content("{\"role\": \"role123\"}")
                .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(document("user-role-create"));
    MockHttpServletResponse response = resultActions
            .andReturn()
            .getResponse();
    assertThat(response.getContentAsByteArray())
            .isEqualTo(objectMapper.writeValueAsBytes(UserRestData.builder().fromUserEntity(user).build()));
    verify(userAdminService).addRoleToUser("user123", "role123");
}
项目:theskeleton    文件:RoleRestControllerTest.java   
@Test
public void testSaveRole() throws Exception {
    RoleEntity input = new RoleEntity()
            .setId("123")
            .setCode("12345")
            .setDescription("Description 12345");
    RoleEntity dbResult = new RoleEntity()
            .setId(UUID.randomUUID().toString())
            .setCode("12345")
            .setDescription("Description 12345");
    byte[] jsonInput = objectMapper.writeValueAsBytes(RoleRestData.builder().fromRoleEntity(input).build());
    when(roleService.saveRole(any())).thenReturn(dbResult);
    ResultActions resultActions = mockMvc.perform(post("/api/roles")
                .contentType(MediaType.APPLICATION_JSON)
                .content(jsonInput))
            .andExpect(status().isOk())
            .andDo(document("role-create"));
    MockHttpServletResponse response = resultActions
            .andReturn()
            .getResponse();
    verify(roleService).saveRole(any());
    assertThat(response.getContentAsByteArray())
            .isEqualTo(objectMapper.writeValueAsBytes(RoleRestData.builder().fromRoleEntity(dbResult).build()));
}
项目:devops-cstack    文件:SecurityTestIT.java   
/**
 * The First test 00 is only for User1
 * @throws Exception
 */
@Test
public void test00_createApplicationUser1() throws Exception {
    logger.info("*********************************");
    logger.info(" Create an application for User1 ");
    logger.info("*********************************");
    final String jsonString = "{\"applicationName\":\""+applicationName
            + "\", \"serverName\":\""+"tomcat-8"+"\"}";
    ResultActions resultats = this.mockMvc
            .perform(
                post("/application").session(session1)
                            .contentType(MediaType.APPLICATION_JSON)
                            .content(jsonString));
    resultats.andExpect(status().isOk());

    logger.info("*********************************");
    logger.info(" Delete the application for User1 ");
    logger.info("*********************************");
    resultats = this.mockMvc
            .perform(
                    delete("/application/" + applicationName).session(session1)
                            .contentType(MediaType.APPLICATION_JSON)
                            .content(jsonString)).andDo(print());
    resultats.andExpect(status().isOk());
}
项目:GitHub    文件:FastJsonHttpMessageConverterJSONPCaseTest.java   
@Test
public void test1_2() throws Exception {


    ResultActions actions = mockMvc.perform((post("/jsonp-fastjsonview/test1?callback=fnUpdateSome").characterEncoding(
            "UTF-8").contentType(MediaType.APPLICATION_JSON)));
    actions.andDo(print());
    actions.andExpect(status().isOk()).andExpect(content().contentType(APPLICATION_JAVASCRIPT))
            .andExpect(content().string("/**/fnUpdateSome({\"id\":100,\"name\":\"测试\"})"));
}
项目:devops-cstack    文件:VolumeControllerTestIT.java   
private ResultActions createVolume(VolumeResource volumeResource) throws Exception {
    // Convert the pojo to a String to use it as content for url call
    String requestJson = getString(volumeResource, mapper);

    // call the api
    logger.info("Create Volume : " + volumeResource.getName());
    ResultActions resultats =
            mockMvc.perform(post("/volume").session(session).contentType(MediaType.APPLICATION_JSON).content(requestJson));
    return resultats;
}
项目:spring-boot-readiness    文件:ReadinessControllerTest.java   
@Test
@SneakyThrows
public void should_render_dashboard_using_default_sorting() {
    // GIVEN
    givenReadinessResponse();

    // WHEN
    ResultActions resultActions = mockMvc.perform(get("/readiness.html").accept(TEXT_HTML));

    // THEN
    resultActions
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(TEXT_HTML))
            .andExpect(content().string(containsString("<tt>test platform</tt>")));
}
项目:GitHub    文件:FastJsonHttpMessageConverterJSONPCaseTest.java   
@Test
public void test5_2() throws Exception {

    String jsonStr = "{\"packet\":{\"smsType\":\"USER_LOGIN\"}}";

    ResultActions actions = mockMvc.perform((post("/jsonp-fastjsonview/test5?callback=myUpdate").characterEncoding("UTF-8")
            .content(jsonStr).contentType(MediaType.APPLICATION_JSON)));
    actions.andDo(print());
    actions.andExpect(status().isOk())
            .andExpect(content().contentType(APPLICATION_JAVASCRIPT))
            .andExpect(content().string("/**/myUpdate(\"{\\\"packet\\\":{\\\"smsType\\\":\\\"USER_LOGIN\\\"}}\")"));
}
项目:devops-cstack    文件:Apache2ControllerTestIT.java   
@After
public void teardown() throws Exception {
    logger.info("teardown");

    ResultActions resultats =
            mockMvc.perform(delete("/application/" + applicationName).session(session).contentType(MediaType.APPLICATION_JSON));
    resultats.andExpect(status().isOk());

    SecurityContextHolder.clearContext();
    session.invalidate();
}
项目:NGB-master    文件:ExternalDBControllerTest.java   
@Test
public void testFetchEnsemblData() throws Exception {
    // arrange
    String fetchRes = readFile("ensembl_lookup_id_ENSG00000106683.json");

    when(
            httpDataManager.fetchData(Mockito.anyString(), Mockito.any(ParameterNameValue[].class))
    ).thenReturn(fetchRes);

    // act
    ResultActions actions = mvc
            .perform(get(String.format(URL_FETCH_ENSEMBL_DATA, "rs7412"))
                    .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()));

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

    EnsemblEntryVO ensemblEntryVO = res.getPayload();

    // assert
    Assert.assertNotNull(ensemblEntryVO);
    Assert.assertEquals("ENSG00000106683", ensemblEntryVO.getId());
    Assert.assertTrue(ensemblEntryVO.getStart().equals(GENE_START));
    Assert.assertTrue(ensemblEntryVO.getEnd().equals(END));
    Assert.assertEquals("GRCh38", ensemblEntryVO.getAssemblyName());
    Assert.assertEquals("LIMK1", ensemblEntryVO.getDisplayName());
    Assert.assertEquals("LIM domain kinase 1 [Source:HGNC Symbol;Acc:HGNC:6613]", ensemblEntryVO.getDescription());
}
项目:GitHub    文件:FastJsonpHttpMessageConverter4Case2Test.java   
@Test
public void test2_2() throws Exception {

    String jsonStr = "[{\"name\":\"p1\",\"sonList\":[{\"name\":\"s1\"}]},{\"name\":\"p2\",\"sonList\":[{\"name\":\"s2\"},{\"name\":\"s3\"}]}]";

    ResultActions actions = mockMvc.perform((post("/fastjson/test2?jsonp=fnUpdateSome").characterEncoding("UTF-8")
            .content(jsonStr).contentType(MediaType.APPLICATION_JSON)));
    actions.andDo(print());
    actions.andExpect(status().isOk()).andExpect(content().contentType(APPLICATION_JAVASCRIPT))
            .andExpect(content().string("/**/fnUpdateSome({\"p1\":1,\"p2\":2})"));
}
项目:devops-cstack    文件:ModulesControllerTestIT.java   
private ResultActions requestAddModule(String module) throws Exception {
    String jsonString = "{\"applicationName\":\"" + applicationName + "\", \"imageName\":\"" + module + "\"}";
    return mockMvc.perform(post("/module")
            .session(session)
            .contentType(MediaType.APPLICATION_JSON)
            .content(jsonString))
            .andDo(print());
}
项目:GitHub    文件:FastJsonpHttpMessageConverter4Case2Test.java   
@Test
public void test5_2() throws Exception {

    String jsonStr = "{\"packet\":{\"smsType\":\"USER_LOGIN\"}}";

    ResultActions actions = mockMvc.perform((post("/fastjson/test5?callback=myUpdate").characterEncoding("UTF-8")
            .content(jsonStr).contentType(MediaType.APPLICATION_JSON)));
    actions.andDo(print());
    actions.andExpect(status().isOk())
            .andExpect(content().contentType(APPLICATION_JAVASCRIPT))
            .andExpect(content().string("/**/myUpdate(\"{\\\"packet\\\":{\\\"smsType\\\":\\\"USER_LOGIN\\\"}}\")"));
}
项目:Spring-Boot-Examples    文件:TodoControllerTest.java   
@Test
public void shouldReturn404WhenTryPartialUpdateTodoWhichNotExists() throws Exception {
    // Given
    given(todoService.getTodoById(anyLong())).willReturn(null);
    HashMap<String, Object> updates = new HashMap<>();
    updates.put("description", "new description");
    // When
    ResultActions result = this.mvc.perform(patch("/todos/10")
            .contentType(MediaType.APPLICATION_JSON_VALUE)
            .content(objectMapper.writeValueAsString(updates)));
    // Then
    result.andExpect(status().isNotFound());
}
项目:cloud-s4-sdk-examples    文件:HealthEndpointIntegrationTest.java   
@Test
public void testStaticFile() throws Exception {
    mockSdk.requestContextExecutor().execute(new Executable() {
        @Override
        public void execute() throws Exception {
            final ResultActions action = mockMvc.perform(MockMvcRequestBuilders.get("/index.html"));
            action.andExpect(MockMvcResultMatchers.status().isOk());
        }
    });
}
项目:GitHub    文件:FastJsonpHttpMessageConverter4Case3Test.java   
@Test
public void test4_2() throws Exception {

    String jsonStr = "{\"t\":{\"id\":123,\"name\":\"哈哈哈\"}}";

    ResultActions actions = mockMvc.perform((post("/fastjson/test4?callback=myUpdate").characterEncoding("UTF-8")
            .content(jsonStr).contentType(MediaType.APPLICATION_JSON)));
    actions.andDo(print());
    actions.andExpect(status().isOk())
            .andExpect(content().contentType(APPLICATION_JAVASCRIPT))
            .andExpect(content().string("/**/myUpdate(\"{\\\"t\\\":{\\\"id\\\":123,\\\"name\\\":\\\"哈哈哈\\\"}}\")"));
}
项目:devops-cstack    文件:NameApplicationTestIT.java   
@Test
public void test014_FailCreateSpecialsSpecialsCharApplication()
        throws Exception {
    logger.info("Create application with an only specials characters name");
    final String jsonString = "{\"applicationName\":\"" + "©доあ" + "\", \"serverName\":\"" + release + "\"}";
    ResultActions resultats =
            this.mockMvc.perform(post("/application")
                    .session(session)
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(jsonString));
    resultats.andExpect(status().is5xxServerError());
}