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


Java MockMvc類代碼示例

本文整理匯總了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));
}
 
開發者ID:deepu105,項目名稱:spring-io,代碼行數:19,代碼來源:WebConfigurerTest.java

示例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));
}
 
開發者ID:oktadeveloper,項目名稱:jhipster-microservices-example,代碼行數:17,代碼來源:ExceptionTranslatorTest.java

示例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());
}
 
開發者ID:Vapsel,項目名稱:social-media-analytic-system,代碼行數:22,代碼來源:ControllersTest.java

示例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;
    }
 
開發者ID:aollio,項目名稱:school-express-delivery,代碼行數:27,代碼來源:TestUtil.java

示例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");
}
 
開發者ID:HewlettPackard,項目名稱:loom,代碼行數:17,代碼來源:IntegrationTestBase.java

示例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)));

}
 
開發者ID:cloudfoundry-incubator,項目名稱:credhub,代碼行數:23,代碼來源:RequestHelper.java

示例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();
}
 
開發者ID:philwebb,項目名稱:spring-boot-concourse,代碼行數:18,代碼來源:MetricFilterAutoConfigurationTests.java

示例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();
}
 
開發者ID:philwebb,項目名稱:spring-boot-concourse,代碼行數:18,代碼來源:MetricFilterAutoConfigurationTests.java

示例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;
}
 
開發者ID:cloudfoundry-incubator,項目名稱:credhub,代碼行數:23,代碼來源:RequestHelper.java

示例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());
}
 
開發者ID:DISID,項目名稱:springlets,代碼行數:28,代碼來源:SpringletsImageFileConverterAutoConfigurationTest.java

示例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;
}
 
開發者ID:sw360,項目名稱:sw360rest,代碼行數:21,代碼來源:TestHelper.java


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