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

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

本文整理了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

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

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

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

代码示例

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

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

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

  1. protected final MockMvc createMockMvc(Filter[] filters, MockServletConfig servletConfig,
  2. WebApplicationContext webAppContext, @Nullable RequestBuilder defaultRequestBuilder,
  3. List<ResultMatcher> globalResultMatchers, List<ResultHandler> globalResultHandlers,
  4. @Nullable List<DispatcherServletCustomizer> dispatcherServletCustomizers) {
  5. TestDispatcherServlet dispatcherServlet = new TestDispatcherServlet(webAppContext);
  6. if (dispatcherServletCustomizers != null) {
  7. for (DispatcherServletCustomizer customizers : dispatcherServletCustomizers) {
  8. customizers.customize(dispatcherServlet);
  9. }
  10. }
  11. try {
  12. dispatcherServlet.init(servletConfig);
  13. }
  14. catch (ServletException ex) {
  15. // should never happen..
  16. throw new MockMvcBuildException("Failed to initialize TestDispatcherServlet", ex);
  17. }
  18. MockMvc mockMvc = new MockMvc(dispatcherServlet, filters);
  19. mockMvc.setDefaultRequest(defaultRequestBuilder);
  20. mockMvc.setGlobalResultMatchers(globalResultMatchers);
  21. mockMvc.setGlobalResultHandlers(globalResultHandlers);
  22. return mockMvc;
  23. }

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

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

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

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

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

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

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

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

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

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

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

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

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

  1. @Test
  2. public void testFeedWithLinefeedChars() throws Exception {
  3. // Map<String, String> namespace = Collections.singletonMap("ns", "");
  4. standaloneSetup(new BlogFeedController()).build()
  5. .perform(get("/blog.atom").accept(MediaType.APPLICATION_ATOM_XML))
  6. .andExpect(status().isOk())
  7. .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_ATOM_XML))
  8. .andExpect(xpath("//feed/title").string("Test Feed"))
  9. .andExpect(xpath("//feed/icon").string("http://www.example.com/favicon.ico"));
  10. }

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

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

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

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

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

  1. .build();
  2. mockMvc.perform(get("/person/Corea"))
  3. .andExpect(status().isOk())
  4. .andExpect(model().size(1))
  5. .andExpect(model().attributeExists("person"))
  6. .andExpect(forwardedUrl("person/show"));
  7. mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_JSON))
  8. .andExpect(status().isOk())
  9. .andExpect(content().contentType(MediaType.APPLICATION_JSON))
  10. .andExpect(jsonPath("$.person.name").value("Corea"));
  11. mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_XML))
  12. .andExpect(status().isOk())
  13. .andExpect(content().contentType(MediaType.APPLICATION_XML))
  14. .andExpect(xpath("/person/name/text()").string(equalTo("Corea")));

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

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

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

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

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

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

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

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

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

  1. @Test
  2. public void requestWhenSessionManagementConfiguredThenUserConfigurationOverrides()
  3. throws Exception {
  4. this.spring.register(RestOperationsConfig.class, AlwaysSessionCreationConfig.class, BasicController.class).autowire();
  5. mockRestOperations(jwks("Default"));
  6. String token = this.token("ValidNoScopes");
  7. MvcResult result = this.mvc.perform(get("/")
  8. .with(bearerToken(token)))
  9. .andExpect(status().isOk())
  10. .andReturn();
  11. assertThat(result.getRequest().getSession(false)).isNotNull();
  12. }

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

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

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

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

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

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

相关文章