當前位置: 首頁>>代碼示例>>Java>>正文


Java MockHttpServletRequestBuilder類代碼示例

本文整理匯總了Java中org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder的典型用法代碼示例。如果您正苦於以下問題:Java MockHttpServletRequestBuilder類的具體用法?Java MockHttpServletRequestBuilder怎麽用?Java MockHttpServletRequestBuilder使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


MockHttpServletRequestBuilder類屬於org.springframework.test.web.servlet.request包,在下文中一共展示了MockHttpServletRequestBuilder類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testList

import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; //導入依賴的package包/類
@Test
public void testList() throws Exception {
    //創建書架創建的請求
    //請求方式為post
    MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.post("/store/list.do");
    //有些參數我注釋掉了,你可以自行添加相關參數,得到不同的測試結果
    //status為0的記錄
    //mockHttpServletRequestBuilder.param("status", "0");
    //書架編號為dd的記錄
    //mockHttpServletRequestBuilder.param("number", "dd");
    //第一頁
    mockHttpServletRequestBuilder.param("page", "1");
    //每頁10條記錄
    mockHttpServletRequestBuilder.param("rows", "10");
    mockMvc.perform(mockHttpServletRequestBuilder).andExpect(status().isOk())
            .andDo(print());

    //控製台會打印如下結果:
    //MockHttpServletResponse:
    //Status = 200 即為後端成功相應
    //返回數據
}
 
開發者ID:ZHENFENG13,項目名稱:ssm-demo,代碼行數:23,代碼來源:StoreControllerTest.java

示例2: testSocialConnections

import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; //導入依賴的package包/類
@Test
@WithMockUser("user123")
public void testSocialConnections() throws Exception {
	LinkedMultiValueMap<String, Connection<?>> connections = new LinkedMultiValueMap<>();
	connections.add(connection.getKey().getProviderId(), connection);
	when(connectionRepository.findAllConnections()).thenReturn(connections);
	MockHttpServletRequestBuilder request = get("/api/profile/socials")
		.contentType(MediaType.APPLICATION_JSON);
	MockHttpServletResponse response = mockMvc.perform(request)
		.andDo(document("user-profile-socials-list"))
		.andReturn()
		.getResponse();
	assertThat(response.getStatus()).isEqualTo(200);
	JsonNode jsonResponse = objectMapper.readTree(response.getContentAsByteArray());
	assertThat(jsonResponse.isObject()).isTrue();
	assertThat(jsonResponse.has(PROVIDER_ID)).isTrue();
	assertThat(jsonResponse.get(PROVIDER_ID).isObject()).isTrue();
	assertThat(jsonResponse.get(PROVIDER_ID).get("imageUrl").textValue()).isEqualTo(connection.getImageUrl());
	verify(connectionRepository).findAllConnections();
}
 
開發者ID:codenergic,項目名稱:theskeleton,代碼行數:21,代碼來源:ProfileSocialRestControllerTest.java

示例3: testFindProfileActiveSessions

import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; //導入依賴的package包/類
@Test
@WithMockUser("user123")
public void testFindProfileActiveSessions() throws Exception {
	final UserEntity user = new UserEntity().setUsername("user123");
	when(sessionRegistry.getAllPrincipals()).thenReturn(Collections.singletonList(user));
	final SessionInformation sessionInformation = new SessionInformation("1", "1", new Date());
	when(sessionRegistry.getAllSessions(user, true))
		.thenReturn(Collections.singletonList(sessionInformation));
	MockHttpServletRequestBuilder request = get("/api/profile/sessions")
		.contentType(MediaType.APPLICATION_JSON);
	MockHttpServletResponse response = mockMvc.perform(request)
		.andDo(document("user-profile-sessions-list"))
		.andReturn()
		.getResponse();
	assertThat(response.getStatus()).isEqualTo(200);
	List<SessionInformation> expectedValue = Collections
		.singletonList(new SessionInformation("user123", "1", sessionInformation.getLastRequest()));
	assertThat(response.getContentAsByteArray()).isEqualTo(objectMapper.writeValueAsBytes(expectedValue));
	verify(sessionRegistry).getAllPrincipals();
	verify(sessionRegistry).getAllSessions(user, true);
}
 
開發者ID:codenergic,項目名稱:theskeleton,代碼行數:22,代碼來源:ProfileRestControllerTest.java

示例4: should_response_4xx_if_flow_name_format_invalid

import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; //導入依賴的package包/類
@Test
public void should_response_4xx_if_flow_name_format_invalid() throws Throwable {
    String flowName = "hello*gmail";

    MockHttpServletRequestBuilder request = get("/flows/" + flowName + "/exist")
        .contentType(MediaType.APPLICATION_JSON);

    MvcResult result = this.mockMvc.perform(request)
        .andExpect(status().is4xxClientError())
        .andReturn();

    String body = result.getResponse().getContentAsString();
    ResponseError error = ResponseError.parse(body, ResponseError.class);
    Assert.assertNotNull(error);
    Assert.assertEquals(error.getMessage(), "Illegal node name: hello*gmail");
}
 
開發者ID:FlowCI,項目名稱:flow-platform,代碼行數:17,代碼來源:FlowControllerTest.java

示例5: testUpdateProfilePassword

import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; //導入依賴的package包/類
@Test
@WithMockUser("user123")
public void testUpdateProfilePassword() throws Exception {
	final UserEntity user = new UserEntity()
		.setId("user123")
		.setUsername("user")
		.setEmail("[email protected]");
	when(profileService.updateProfilePassword(eq("user123"), any())).thenReturn(user);
	MockHttpServletRequestBuilder request = put("/api/profile/password")
		.content("{\"username\": \"user123\"}")
		.contentType(MediaType.APPLICATION_JSON);
	MockHttpServletResponse response = mockMvc.perform(request)
		.andDo(document("user-profile-password-update"))
		.andReturn()
		.getResponse();
	assertThat(response.getStatus()).isEqualTo(200);
	assertThat(response.getContentAsByteArray())
		.isEqualTo(objectMapper.writeValueAsBytes(ProfileRestData.builder().fromUserEntity(user).build()));
	verify(profileService).updateProfilePassword(eq("user123"), any());
}
 
開發者ID:codenergic,項目名稱:theskeleton,代碼行數:21,代碼來源:ProfileRestControllerTest.java

示例6: createDuplicatedTopic

import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; //導入依賴的package包/類
@Test
public void createDuplicatedTopic() throws Exception {
    // Given
    Topic spring = new Topic("spring");
    topicRepository.save(spring);

    TopicDto topicDto = TopicDto.of(spring.getName());

    MockHttpServletRequestBuilder request = post("/api/topic/create")
        .contentType(MediaType.APPLICATION_JSON_UTF8)
        .content(objectMapper.writeValueAsString(topicDto));

    // When & Then
    mvc.perform(request)
        .andDo(print())
        .andDo(document("create-topic-duplicated"))
        .andExpect(status().isConflict())
    ;
}
 
開發者ID:spring-sprout,項目名稱:osoon,代碼行數:20,代碼來源:TopicControllerTest.java

示例7: testFindClientById

import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; //導入依賴的package包/類
@Test
@WithMockUser("user123")
public void testFindClientById() throws Exception {
	final OAuth2ClientEntity client = new OAuth2ClientEntity()
		.setId("client123")
		.setName("client")
		.setDescription("description")
		.setClientSecret("123456secret")
		.setSecretRequired(true)
		.setAutoApprove(false)
		.setAuthorizedGrantTypes(new HashSet<>(Arrays.asList(AUTHORIZATION_CODE, IMPLICIT)));
	when(oAuth2ClientService.findClientById("client123")).thenReturn(client);
	MockHttpServletRequestBuilder request = get("/api/clients/client123")
		.contentType(MediaType.APPLICATION_JSON);
	MockHttpServletResponse response = mockMvc.perform(request)
		.andExpect(status().isOk())
		.andDo(document("client-read"))
		.andReturn()
		.getResponse();
	assertThat(response.getContentAsByteArray())
		.isEqualTo(objectMapper.writeValueAsBytes(OAuth2ClientRestData.builder()
				.fromOAuth2ClientEntity(client).build()));
	verify(oAuth2ClientService).findClientById("client123");
}
 
開發者ID:codenergic,項目名稱:theskeleton,代碼行數:25,代碼來源:OAuth2ClientRestControllerTest.java

示例8: testFindClients

import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; //導入依賴的package包/類
@Test
@WithMockUser("user123")
public void testFindClients() throws Exception {
	final OAuth2ClientEntity client = new OAuth2ClientEntity()
		.setId("client123")
		.setName("client")
		.setDescription("description")
		.setClientSecret("123456secret")
		.setSecretRequired(true)
		.setAutoApprove(false)
		.setAuthorizedGrantTypes(new HashSet<>(Arrays.asList(AUTHORIZATION_CODE, IMPLICIT)));
	Page<OAuth2ClientEntity> clients = new PageImpl<>(Arrays.asList(client));
	when(oAuth2ClientService.findClients(anyString(), any())).thenReturn(clients);
	MockHttpServletRequestBuilder request = get("/api/clients")
		.contentType(MediaType.APPLICATION_JSON);
	MockHttpServletResponse response = mockMvc.perform(request)
		.andExpect(status().isOk())
		.andDo(document("client-read-all"))
		.andReturn()
		.getResponse();
	assertThat(response.getContentAsByteArray())
		.isEqualTo(objectMapper.writeValueAsBytes(
			clients.map(c -> OAuth2ClientRestData.builder().fromOAuth2ClientEntity(c).build())));
	verify(oAuth2ClientService).findClients(anyString(), any());
}
 
開發者ID:codenergic,項目名稱:theskeleton,代碼行數:26,代碼來源:OAuth2ClientRestControllerTest.java

示例9: testGenerateClientSecret

import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; //導入依賴的package包/類
@Test
@WithMockUser("user123")
public void testGenerateClientSecret() throws Exception {
	final OAuth2ClientEntity client = new OAuth2ClientEntity()
			.setId("client123");
	when(oAuth2ClientService.generateSecret(eq("client123"))).thenReturn(client);
	MockHttpServletRequestBuilder request = put("/api/clients/client123/generate-secret")
		.contentType(MediaType.APPLICATION_JSON);
	MockHttpServletResponse response = mockMvc.perform(request)
		.andExpect(status().isOk())
		.andDo(document("client-generate-secret"))
		.andReturn()
		.getResponse();
	assertThat(response.getContentAsByteArray())
	.isEqualTo(objectMapper.writeValueAsBytes(OAuth2ClientRestData.builder()
			.fromOAuth2ClientEntity(client).build()));
	verify(oAuth2ClientService).generateSecret(eq("client123"));
}
 
開發者ID:codenergic,項目名稱:theskeleton,代碼行數:19,代碼來源:OAuth2ClientRestControllerTest.java

示例10: testSaveClient

import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; //導入依賴的package包/類
@Test
@WithMockUser("user123")
public void testSaveClient() throws Exception {
	final OAuth2ClientEntity client = new OAuth2ClientEntity()
			.setId("client123")
			.setName("client")
			.setDescription("description")
			.setSecretRequired(true)
			.setAutoApprove(false)
			.setAuthorizedGrantTypes(new HashSet<>(Arrays.asList(AUTHORIZATION_CODE, IMPLICIT)));
	when(oAuth2ClientService.saveClient(any())).thenReturn(client);
	MockHttpServletRequestBuilder request = post("/api/clients")
			.content("{\"name\": \"client\", \"description\": \"description\", "
					+ "\"isSecretRequired\": true, \"isAutoApprove\": false, "
					+ "\"authorizedGrantTypes\": [\"AUTHORIZATION_CODE\",\"IMPLICIT\"]}")
		.contentType(MediaType.APPLICATION_JSON);
	MockHttpServletResponse response = mockMvc.perform(request)
		.andExpect(status().isOk())
		.andDo(document("client-create"))
		.andReturn()
		.getResponse();
	assertThat(response.getContentAsByteArray())
		.isEqualTo(objectMapper.writeValueAsBytes(OAuth2ClientRestData.builder()
			.fromOAuth2ClientEntity(client).build()));
	verify(oAuth2ClientService).saveClient(any());
}
 
開發者ID:codenergic,項目名稱:theskeleton,代碼行數:27,代碼來源:OAuth2ClientRestControllerTest.java

示例11: testUpdateClient

import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; //導入依賴的package包/類
@Test
@WithMockUser("user123")
public void testUpdateClient() throws Exception {
	final OAuth2ClientEntity client = new OAuth2ClientEntity()
			.setId("client123");
	when(oAuth2ClientService.updateClient(eq("client123"), any())).thenReturn(client);
	MockHttpServletRequestBuilder request = put("/api/clients/client123")
		.content("{\"name\": \"client\", \"description\": \"description\", \"clientSecret\": \"s3cret\", "
				+ "\"isSecretRequired\": true, \"isAutoApprove\": false, "
				+ "\"authorizedGrantTypes\": [\"AUTHORIZATION_CODE\",\"IMPLICIT\"]}")
		.contentType(MediaType.APPLICATION_JSON);
	MockHttpServletResponse response = mockMvc.perform(request)
		.andExpect(status().isOk())
		.andDo(document("client-update"))
		.andReturn()
		.getResponse();
	assertThat(response.getContentAsByteArray())
	.isEqualTo(objectMapper.writeValueAsBytes(OAuth2ClientRestData.builder()
			.fromOAuth2ClientEntity(client).build()));
	verify(oAuth2ClientService).updateClient(eq("client123"), any());
}
 
開發者ID:codenergic,項目名稱:theskeleton,代碼行數:22,代碼來源:OAuth2ClientRestControllerTest.java

示例12: testRegister

import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; //導入依賴的package包/類
@Test
public void testRegister() throws Exception {
	final RegistrationForm form = new RegistrationForm()
			.setUsername("test123")
			.setPassword("12345678")
			.setEmail("[email protected]");
	final UserEntity user = new UserEntity().setId("123");
	when(registrationService.registerUser(any())).thenReturn(user);
	MockHttpServletRequestBuilder request = post("/api/register")
			.content("{\"username\": \"test123\", \"password\": \"12345678\", "
					+ "\"email\": \"[email protected]\"}")
		.contentType(MediaType.APPLICATION_JSON);
	MockHttpServletResponse response = mockMvc.perform(request)
		.andExpect(status().isOk())
		.andDo(document("registration"))
		.andReturn()
		.getResponse();
	assertThat(response.getContentAsByteArray())
		.isEqualTo(objectMapper.writeValueAsBytes(form));
	verify(registrationService).registerUser(any());
}
 
開發者ID:codenergic,項目名稱:theskeleton,代碼行數:22,代碼來源:RegistrationRestControllerTest.java

示例13: createRequestBuilderWithMethodAndUri

import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; //導入依賴的package包/類
protected MockHttpServletRequestBuilder createRequestBuilderWithMethodAndUri(Pact.InteractionRequest request) throws Exception {
    String uri = request.getUri().contains(getServletContextPathWithoutTrailingSlash())
            ? StringUtils.substringAfter(request.getUri(), getServletContextPathWithoutTrailingSlash())
            : request.getUri();
    uri = UriUtils.decode(uri, "UTF-8");

    switch (request.getMethod()) {
        case GET:
            return get(uri);
        case POST:
            return post(uri);
        case PUT:
            return put(uri);
        case DELETE:
            return delete(uri);
        default:
            throw new RuntimeException("Unsupported method " + request.getMethod());
    }
}
 
開發者ID:tyro,項目名稱:pact-spring-mvc,代碼行數:20,代碼來源:PactTestBase.java

示例14: getHttpResultContent

import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; //導入依賴的package包/類
public static MvcResult getHttpResultContent(MockMvc mockMvc, String uri, Method method, Map<String, String> keyvals) throws Exception {

        MockHttpServletRequestBuilder builder = null;
        switch (method) {
            case GET:
                builder = MockMvcRequestBuilders.get(uri);
                break;
            case POST:
                builder = MockMvcRequestBuilders.post(uri);
                break;
            case PUT:
                builder = MockMvcRequestBuilders.put(uri);
                break;
            case DELETE:
                builder = MockMvcRequestBuilders.delete(uri);
                break;
            default:
                builder = MockMvcRequestBuilders.get(uri);
        }
        for (Map.Entry<String, String> entry : keyvals.entrySet()) {
            builder = builder.param(entry.getKey(), entry.getValue());
        }
        MvcResult result = mockMvc.perform(builder.accept(MediaType.ALL)).andReturn();
//        result.getResponse().getHeaderNames();
        return result;
    }
 
開發者ID:aollio,項目名稱:school-express-delivery,代碼行數:27,代碼來源:TestUtil.java

示例15: testGetUsersPage0Size1

import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; //導入依賴的package包/類
@Test
public void testGetUsersPage0Size1() throws Exception {
    final MockHttpServletRequestBuilder getRequest = get(UserController.REQUEST_PATH_API_USERS)
            .param("size", "1")
            .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("$.content", Matchers.hasSize(1)))
            .andExpect(jsonPath("$.content[0].email").value("[email protected]"))
            .andExpect(jsonPath("$.totalElements").value(2))
            .andExpect(jsonPath("$.totalPages").value(2))
            .andExpect(jsonPath("$.size").value(1))
            .andExpect(jsonPath("$.number").value(0))
            .andExpect(jsonPath("$.first").value("true"))
            .andExpect(jsonPath("$.last").value("false"));
}
 
開發者ID:karlkyck,項目名稱:spring-boot-completablefuture,代碼行數:25,代碼來源:UserControllerIntTest.java


注:本文中的org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。