org.springframework.test.web.servlet.MockMvc类的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(10.2k)|赞(0)|评价(0)|浏览(103)

本文整理了Java中org.springframework.test.web.servlet.MockMvc类的一些代码示例,展示了MockMvc类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。MockMvc类的具体详情如下:
包路径:org.springframework.test.web.servlet.MockMvc
类名称:MockMvc

MockMvc介绍

[英]Main entry point for server-side Spring MVC test support.

Example

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; 
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*; 
// ... 
WebApplicationContext wac = ...; 
MockMvc mockMvc = webAppContextSetup(wac).build(); 
mockMvc.perform(get("/form")) 
.andExpect(status().isOk()) 
.andExpect(content().mimeType("text/html")) 
.andExpect(forwardedUrl("/WEB-INF/layouts/main.jsp"));

[中]服务器端Spring MVC测试支持的主要入口点。
####范例

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; 
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*; 
// ... 
WebApplicationContext wac = ...; 
MockMvc mockMvc = webAppContextSetup(wac).build(); 
mockMvc.perform(get("/form")) 
.andExpect(status().isOk()) 
.andExpect(content().mimeType("text/html")) 
.andExpect(forwardedUrl("/WEB-INF/layouts/main.jsp"));

代码示例

代码示例来源:origin: spring-projects/spring-framework

@Test  // SPR-13079
public void deferredResultWithDelayedError() throws Exception {
  MvcResult mvcResult = this.mockMvc.perform(get("/1").param("deferredResultWithDelayedError", "true"))
      .andExpect(request().asyncStarted())
      .andReturn();
  this.mockMvc.perform(asyncDispatch(mvcResult))
      .andExpect(status().is5xxServerError())
      .andExpect(content().string("Delayed Error"));
}

代码示例来源:origin: spring-projects/spring-framework

protected final MockMvc createMockMvc(Filter[] filters, MockServletConfig servletConfig,
    WebApplicationContext webAppContext, @Nullable RequestBuilder defaultRequestBuilder,
    List<ResultMatcher> globalResultMatchers, List<ResultHandler> globalResultHandlers,
    @Nullable List<DispatcherServletCustomizer> dispatcherServletCustomizers) {
  TestDispatcherServlet dispatcherServlet = new TestDispatcherServlet(webAppContext);
  if (dispatcherServletCustomizers != null) {
    for (DispatcherServletCustomizer customizers : dispatcherServletCustomizers) {
      customizers.customize(dispatcherServlet);
    }
  }
  try {
    dispatcherServlet.init(servletConfig);
  }
  catch (ServletException ex) {
    // should never happen..
    throw new MockMvcBuildException("Failed to initialize TestDispatcherServlet", ex);
  }
  MockMvc mockMvc = new MockMvc(dispatcherServlet, filters);
  mockMvc.setDefaultRequest(defaultRequestBuilder);
  mockMvc.setGlobalResultMatchers(globalResultMatchers);
  mockMvc.setGlobalResultHandlers(globalResultHandlers);
  return mockMvc;
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void tilesDefinitions() throws Exception {
  this.mockMvc.perform(get("/"))
    .andExpect(status().isOk())
    .andExpect(forwardedUrl("/WEB-INF/layouts/standardLayout.jsp"));
}

代码示例来源:origin: spring-projects/spring-framework

@Test
void springMvcTest(WebApplicationContext wac) throws Exception {
  webAppContextSetup(wac).build()
    .perform(get("/person/42").accept(MediaType.APPLICATION_JSON))
    .andExpect(status().isOk())
    .andExpect(jsonPath("$.name", is("Dilbert")));
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void multipartRequestWithSingleFileNotPresent() throws Exception {
  standaloneSetup(new MultipartController()).build()
      .perform(multipart("/multipartfile"))
      .andExpect(status().isFound());
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void saveSpecial() throws Exception {
  this.mockMvc.perform(post("/people").param("name", "Andy"))
      .andExpect(status().isFound())
      .andExpect(redirectedUrl("/persons/Joe"))
      .andExpect(model().size(1))
      .andExpect(model().attributeExists("name"))
      .andExpect(flash().attributeCount(1))
      .andExpect(flash().attribute("message", "success!"));
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void person() throws Exception {
  this.mockMvc.perform(get("/person/5").accept(MediaType.APPLICATION_JSON))
    .andDo(print())
    .andExpect(status().isOk())
    .andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testContentAsString() throws Exception {
  this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN))
    .andExpect(content().string("Hello world!"));
  this.mockMvc.perform(get("/handleUtf8"))
    .andExpect(content().string("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01"));
  // Hamcrest matchers...
  this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN)).andExpect(content().string(equalTo("Hello world!")));
  this.mockMvc.perform(get("/handleUtf8")).andExpect(content().string(equalTo("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01")));
}

代码示例来源:origin: spring-projects/spring-framework

@Test
  public void testFeedWithLinefeedChars() throws Exception {

//        Map<String, String> namespace = Collections.singletonMap("ns", "");

    standaloneSetup(new BlogFeedController()).build()
      .perform(get("/blog.atom").accept(MediaType.APPLICATION_ATOM_XML))
        .andExpect(status().isOk())
        .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_ATOM_XML))
        .andExpect(xpath("//feed/title").string("Test Feed"))
        .andExpect(xpath("//feed/icon").string("http://www.example.com/favicon.ico"));
  }

代码示例来源:origin: spring-projects/spring-framework

@Test
public void stringWithMissingResponseHeader() throws Exception {
  this.mockMvc.perform(get("/persons/1").header(IF_MODIFIED_SINCE, now))
      .andExpect(status().isNotModified())
      .andExpect(header().stringValues("X-Custom-Header"));
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void getWhenAcceptHeaderIsApplicationXhtmlXmlThenRespondsWith302() throws Exception {
  this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
  this.mvc.perform(get("/")
      .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XHTML_XML))
      .andExpect(status().isFound());
}

代码示例来源:origin: spring-projects/spring-framework

.build();
mockMvc.perform(get("/person/Corea"))
  .andExpect(status().isOk())
  .andExpect(model().size(1))
  .andExpect(model().attributeExists("person"))
  .andExpect(forwardedUrl("person/show"));
mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_JSON))
  .andExpect(status().isOk())
  .andExpect(content().contentType(MediaType.APPLICATION_JSON))
  .andExpect(jsonPath("$.person.name").value("Corea"));
mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_XML))
  .andExpect(status().isOk())
  .andExpect(content().contentType(MediaType.APPLICATION_XML))
  .andExpect(xpath("/person/name/text()").string(equalTo("Corea")));

代码示例来源:origin: spring-projects/spring-framework

@Test
public void saveWithErrors() throws Exception {
  this.mockMvc.perform(post("/persons"))
    .andExpect(status().isOk())
    .andExpect(forwardedUrl("persons/add"))
    .andExpect(model().size(1))
    .andExpect(model().attributeExists("person"))
    .andExpect(flash().attributeCount(0));
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void stringWithMatcherAndCorrectResponseHeaderValue() throws Exception {
  this.mockMvc.perform(get("/persons/1").header(IF_MODIFIED_SINCE, minuteAgo))
      .andExpect(header().string(LAST_MODIFIED, equalTo(now)));
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void getPerson() throws Exception {
  this.mockMvc.perform(get("/persons/Joe").flashAttr("message", "success!"))
    .andExpect(status().isOk())
    .andExpect(forwardedUrl("persons/index"))
    .andExpect(model().size(2))
    .andExpect(model().attribute("person", new Person("Joe")))
    .andExpect(model().attribute("message", "success!"))
    .andExpect(flash().attributeCount(0));
}

代码示例来源:origin: spring-projects/spring-security

/**
 * http@realm equivalent
 */
@Test
public void basicAuthenticationWhenUsingCustomRealmThenMatchesNamespace() throws Exception {
  this.spring.register(CustomHttpBasicConfig.class, UserConfig.class).autowire();
  this.mvc.perform(get("/")
      .with(httpBasic("user", "invalid")))
      .andExpect(status().isUnauthorized())
      .andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Custom Realm\""));
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void requestWhenSessionManagementConfiguredThenUserConfigurationOverrides()
    throws Exception {
  this.spring.register(RestOperationsConfig.class, AlwaysSessionCreationConfig.class, BasicController.class).autowire();
  mockRestOperations(jwks("Default"));
  String token = this.token("ValidNoScopes");
  MvcResult result = this.mvc.perform(get("/")
      .with(bearerToken(token)))
      .andExpect(status().isOk())
      .andReturn();
  assertThat(result.getRequest().getSession(false)).isNotNull();
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testHttpStatus() throws Exception {
  this.mockMvc.perform(get("/created")).andExpect(status().isCreated());
  this.mockMvc.perform(get("/createdWithComposedAnnotation")).andExpect(status().isCreated());
  this.mockMvc.perform(get("/badRequest")).andExpect(status().isBadRequest());
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void filterWithExactMapping() throws Exception {
  standaloneSetup(new PersonController())
    .addFilter(new RedirectFilter(), "/p", "/persons").build()
    .perform(post("/persons").param("name", "Andy"))
      .andExpect(redirectedUrl("/login"));
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testStatusInt() throws Exception {
  this.mockMvc.perform(get("/created")).andExpect(status().is(201));
  this.mockMvc.perform(get("/createdWithComposedAnnotation")).andExpect(status().is(201));
  this.mockMvc.perform(get("/badRequest")).andExpect(status().is(400));
}

相关文章