本文整理汇总了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 即为后端成功相应
//返回数据
}
示例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();
}
示例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);
}
示例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");
}
示例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());
}
示例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())
;
}
示例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");
}
示例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());
}
示例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"));
}
示例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());
}
示例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());
}
示例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());
}
示例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());
}
}
示例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;
}
示例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"));
}