本文整理汇总了Java中org.springframework.test.web.servlet.MockMvc类的典型用法代码示例。如果您正苦于以下问题:Java MockMvc类的具体用法?Java MockMvc怎么用?Java MockMvc使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
MockMvc类属于org.springframework.test.web.servlet包,在下文中一共展示了MockMvc类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testCorsFilterOnOtherPath
import org.springframework.test.web.servlet.MockMvc; //导入依赖的package包/类
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
mockMvc.perform(
get("/test/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
示例2: processValidationErrorTest
import org.springframework.test.web.servlet.MockMvc; //导入依赖的package包/类
@Test
public void processValidationErrorTest() throws Exception {
UserJWTController control = new UserJWTController(null, null);
MockMvc jwtMock = MockMvcBuilders.standaloneSetup(control)
.setControllerAdvice(new ExceptionTranslator())
.build();
MvcResult res = jwtMock.perform(post("/api/authenticate")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL)
.content("{\"username\":\"fakeUsernameTooLongfakeUsernameTooLongfakeUsernameTooLongfakeUsernameTooLong" +
"\",\"password\":\"fakePassword\",\"rememberMe\":false}"))
.andExpect(status().isBadRequest())
.andReturn();
assertThat(res.getResolvedException(), instanceOf(MethodArgumentNotValidException.class));
}
示例3: testAjaxController
import org.springframework.test.web.servlet.MockMvc; //导入依赖的package包/类
public void testAjaxController() throws Exception {
AjaxController controller = new AjaxController();
MockMvc mockMvc = standaloneSetup(controller).build();
String testJson =
"{\"name\":\"First Last\"," +
"\"likes\":{" +
"\"data\":[{" +
"\"name\":\"GeeCON\"," +
"\"about\":\"Java and JVM based technologies, dynamic languages, patterns, distributed " +
"computing and much more...\"," +
"\"id\":\"354953985700\"" +
"}]" +
"}" +
"}";
mockMvc.perform(post("/userJson")
.accept(MediaType.APPLICATION_JSON)
.content(testJson))
.andExpect(status().isAccepted());
}
示例4: getHttpResultContent
import org.springframework.test.web.servlet.MockMvc; //导入依赖的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;
}
示例5: setupMvcClient
import org.springframework.test.web.servlet.MockMvc; //导入依赖的package包/类
protected void setupMvcClient(final WebApplicationContext ctx, final int noOfClients) {
LOG.info("setupMvcClient start");
isMvc = true;
// loadProperties();
clients = new ArrayList<LoomClient>(noOfClients);
for (int i = 0; i < noOfClients; i++) {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
clients.add(new LoomMvcClient(mockMvc));
if (i == 0) {
client = clients.get(0);
}
waitForStartup();
}
LOG.info("setupMvcClient end");
}
示例6: expect404WhileGeneratingCertificate
import org.springframework.test.web.servlet.MockMvc; //导入依赖的package包/类
public static void expect404WhileGeneratingCertificate(MockMvc mockMvc, String certName,
String token, String expectedMessage) throws Exception {
MockHttpServletRequestBuilder certPost = post("/api/v1/data")
.header("Authorization", "Bearer " + token)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
//language=JSON
.content("{\n"
+ " \"name\" : \"" + certName + "\",\n"
+ " \"type\" : \"certificate\",\n"
+ " \"parameters\" : {\n"
+ " \"common_name\" : \"federation\",\n"
+ " \"ca\" : \"picard\"\n"
+ " }\n"
+ "}");
mockMvc.perform(certPost)
.andDo(print())
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.error", equalTo(expectedMessage)));
}
示例7: gaugeServiceThatThrows
import org.springframework.test.web.servlet.MockMvc; //导入依赖的package包/类
@Test
public void gaugeServiceThatThrows() throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
Config.class, MetricFilterAutoConfiguration.class);
GaugeService gaugeService = context.getBean(GaugeService.class);
willThrow(new IllegalStateException()).given(gaugeService).submit(anyString(),
anyDouble());
Filter filter = context.getBean(Filter.class);
MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController())
.addFilter(filter).build();
mvc.perform(get("/templateVarTest/foo")).andExpect(status().isOk());
verify(context.getBean(CounterService.class))
.increment("status.200.templateVarTest.someVariable");
verify(context.getBean(GaugeService.class))
.submit(eq("response.templateVarTest.someVariable"), anyDouble());
context.close();
}
示例8: agentServletWithCustomPath
import org.springframework.test.web.servlet.MockMvc; //导入依赖的package包/类
@Test
public void agentServletWithCustomPath() throws Exception {
this.context = new AnnotationConfigEmbeddedWebApplicationContext();
EnvironmentTestUtils.addEnvironment(this.context,
"endpoints.jolokia.path=/foo/bar");
this.context.register(EndpointsConfig.class, WebMvcAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
JolokiaAutoConfiguration.class);
this.context.refresh();
assertThat(this.context.getBeanNamesForType(JolokiaMvcEndpoint.class)).hasSize(1);
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
mockMvc.perform(MockMvcRequestBuilders.get("/foo/bar"))
.andExpect(MockMvcResultMatchers.content()
.string(Matchers.containsString("\"request\":{\"type\"")));
}
开发者ID:vikrammane23,项目名称:https-github.com-g0t4-jenkins2-course-spring-boot,代码行数:18,代码来源:JolokiaAutoConfigurationTests.java
示例9: records5xxxHttpInteractionsAsSingleMetric
import org.springframework.test.web.servlet.MockMvc; //导入依赖的package包/类
@Test
public void records5xxxHttpInteractionsAsSingleMetric() throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
Config.class, MetricFilterAutoConfiguration.class,
ServiceUnavailableFilter.class);
MetricsFilter filter = context.getBean(MetricsFilter.class);
MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController())
.addFilter(filter)
.addFilter(context.getBean(ServiceUnavailableFilter.class)).build();
mvc.perform(get("/unknownPath/1")).andExpect(status().isServiceUnavailable());
mvc.perform(get("/unknownPath/2")).andExpect(status().isServiceUnavailable());
verify(context.getBean(CounterService.class), times(2))
.increment("status.503.unmapped");
verify(context.getBean(GaugeService.class), times(2))
.submit(eq("response.unmapped"), anyDouble());
context.close();
}
示例10: correctlyRecordsMetricsForDeferredResultResponse
import org.springframework.test.web.servlet.MockMvc; //导入依赖的package包/类
@Test
public void correctlyRecordsMetricsForDeferredResultResponse() throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
Config.class, MetricFilterAutoConfiguration.class);
MetricsFilter filter = context.getBean(MetricsFilter.class);
CountDownLatch latch = new CountDownLatch(1);
MockMvc mvc = MockMvcBuilders
.standaloneSetup(new MetricFilterTestController(latch)).addFilter(filter)
.build();
String attributeName = MetricsFilter.class.getName() + ".StopWatch";
MvcResult result = mvc.perform(post("/create")).andExpect(status().isOk())
.andExpect(request().asyncStarted())
.andExpect(request().attribute(attributeName, is(notNullValue())))
.andReturn();
latch.countDown();
mvc.perform(asyncDispatch(result)).andExpect(status().isCreated())
.andExpect(request().attribute(attributeName, is(nullValue())));
verify(context.getBean(CounterService.class)).increment("status.201.create");
context.close();
}
开发者ID:vikrammane23,项目名称:https-github.com-g0t4-jenkins2-course-spring-boot,代码行数:21,代码来源:MetricFilterAutoConfigurationTests.java
示例11: generateCa
import org.springframework.test.web.servlet.MockMvc; //导入依赖的package包/类
public static String generateCa(MockMvc mockMvc, String caName, String token) throws Exception {
MockHttpServletRequestBuilder caPost = post("/api/v1/data")
.header("Authorization", "Bearer " + token)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
//language=JSON
.content("{\n"
+ " \"name\" : \"" + caName + "\",\n"
+ " \"type\" : \"certificate\",\n"
+ " \"overwrite\": true,\n"
+ " \"parameters\" : {\n"
+ " \"common_name\" : \"federation\",\n"
+ " \"is_ca\" : true,\n"
+ " \"self_sign\" : true\n"
+ " }\n"
+ "}");
String caResult = mockMvc.perform(caPost)
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
return caResult;
}
示例12: defaultHeaderConfiguration
import org.springframework.test.web.servlet.MockMvc; //导入依赖的package包/类
@Test
public void defaultHeaderConfiguration() throws Exception {
this.context = SpringApplication.run(VanillaWebConfiguration.class,
"--server.port=0");
MockMvc mockMvc = MockMvcBuilders
.webAppContextSetup((WebApplicationContext) this.context)
.addFilters((FilterChainProxy) this.context
.getBean("springSecurityFilterChain", Filter.class))
.build();
mockMvc.perform(MockMvcRequestBuilders.get("/"))
.andExpect(MockMvcResultMatchers.header().string("X-Content-Type-Options",
is(notNullValue())))
.andExpect(MockMvcResultMatchers.header().string("X-XSS-Protection",
is(notNullValue())))
.andExpect(MockMvcResultMatchers.header().string("Cache-Control",
is(notNullValue())))
.andExpect(MockMvcResultMatchers.header().string("X-Frame-Options",
is(notNullValue())));
}
开发者ID:vikrammane23,项目名称:https-github.com-g0t4-jenkins2-course-spring-boot,代码行数:20,代码来源:SpringBootWebSecurityConfigurationTests.java
示例13: securityHeadersCanBeDisabled
import org.springframework.test.web.servlet.MockMvc; //导入依赖的package包/类
@Test
public void securityHeadersCanBeDisabled() throws Exception {
this.context = SpringApplication.run(VanillaWebConfiguration.class,
"--server.port=0", "--security.headers.content-type=false",
"--security.headers.xss=false", "--security.headers.cache=false",
"--security.headers.frame=false");
MockMvc mockMvc = MockMvcBuilders
.webAppContextSetup((WebApplicationContext) this.context)
.addFilters(
this.context.getBean("springSecurityFilterChain", Filter.class))
.build();
mockMvc.perform(MockMvcRequestBuilders.get("/"))
.andExpect(MockMvcResultMatchers.status().isUnauthorized())
.andExpect(MockMvcResultMatchers.header()
.doesNotExist("X-Content-Type-Options"))
.andExpect(
MockMvcResultMatchers.header().doesNotExist("X-XSS-Protection"))
.andExpect(MockMvcResultMatchers.header().doesNotExist("Cache-Control"))
.andExpect(
MockMvcResultMatchers.header().doesNotExist("X-Frame-Options"));
}
开发者ID:vikrammane23,项目名称:https-github.com-g0t4-jenkins2-course-spring-boot,代码行数:23,代码来源:SpringBootWebSecurityConfigurationTests.java
示例14: checkConverter
import org.springframework.test.web.servlet.MockMvc; //导入依赖的package包/类
/**
* Perform a POST request to check the {@link SpringletsImageFileConverter} works.
*
* Only the needed autoconfiguration is loaded in order to create
* the Spring Web MVC artifacts to handle the HTTP request.
*
* @see MockServletContext
* @see MockMvc
*/
@Test
public void checkConverter() throws Exception {
EnvironmentTestUtils.addEnvironment(this.context, "springlets.image.management:true");
this.context.setServletContext(new MockServletContext());
this.context.register(TestConfiguration.class);
this.context.refresh();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
// Mock a multipart file to be sended
MockMultipartFile imageFile =
new MockMultipartFile("image", "image1.jpg", "image/jpg", "image1.jpg".getBytes());
mockMvc
.perform(MockMvcRequestBuilders.fileUpload("/persons").file(imageFile)
.param("name", "TESTNAME").param("surname", "TESTSURNAME"))
.andExpect(status().isOk()).andDo(print());
}
示例15: getAccessToken
import org.springframework.test.web.servlet.MockMvc; //导入依赖的package包/类
public static String getAccessToken(MockMvc mockMvc, String username, String password) throws Exception {
String authorizationHeaderValue = "Basic "
+ new String(Base64Utils.encode("trusted-sw360-client:sw360-secret".getBytes()));
MockHttpServletResponse response = mockMvc
.perform(post("/oauth/token")
.header("Authorization", authorizationHeaderValue)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("client_id", "trusted-sw360-client")
.param("client_secret", "sw360-secret")
.param("username", username)
.param("password", password)
.param("grant_type", "password")
.param("scope", "sw360.read"))
.andReturn().getResponse();
return new ObjectMapper()
.readValue(response.getContentAsByteArray(), OAuthToken.class)
.accessToken;
}