springmvc测试

xiaoxiao2021-02-28  94

为集成测试控制器创建Mock MVC

import static org.hamcrest.Matchers.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 

@RunWith(SpringJUnit4ClassRunner.class) 

@SpringApplicationConfiguration( classes = ReadingListApplication.class) @WebAppConfiguration public class MockMvcWebTests { @Autowired private WebApplicationContext webContext; private MockMvc mockMvc; @Before public void setupMockMvc() { mockMvc = MockMvcBuilders .webAppContextSetup(webContext) .build();

}} 

@Test public void homePage() throws Exception {

mockMvc.perform(MockMvcRequestBuilders.get("/readingList")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.view().name("readingList")).andExpect(MockMvcResultMatchers.model().attributeExists("books")).andExpect(MockMvcResultMatchers.model().attribute("books",

Matchers.is(Matchers.empty())));

@Test public void homePage() throws Exception {

1

mockMvc.perform(get("/readingList")) .andExpect(status().isOk()) .andExpect(view().name("readingList")) .andExpect(model().attributeExists("books")) .andExpect(model().attribute("books", is(empty())));

@Test public void postBook() throws Exception { mockMvc.perform(post("/readingList")

执行POST请求

.contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("title", "BOOK TITLE") .param("author", "BOOK AUTHOR") .param("isbn", "1234567890") 5.param("description", "DESCRIPTION"))

.andExpect(status().is3xxRedirection()).andExpect(header().string("Location", "/readingList"));

Book expectedBook = new Book(); expectedBook.setId(1L); expectedBook.setReader("craig"); expectedBook.setTitle("BOOK TITLE"); expectedBook.setAuthor("BOOK AUTHOR"); expectedBook.setIsbn("1234567890"); expectedBook.setDescription("DESCRIPTION"); mockMvc.perform(get("/readingList")) .andExpect(status().isOk())

.andExpect(view().name("readingList")) .andExpect(model().attributeExists("books")) .andExpect(model().attribute("books", hasSize(1))) .andExpect(model().attribute("books", contains(samePropertyValuesAs(expectedBook)))); }

开启安全

@Before public void setupMockMvc() { mockMvc = MockMvcBuilders .webAppContextSetup(webContext) .apply(springSecurity()) .build();

@Test public void homePage_unauthenticatedUser() throws Exception { mockMvc.perform(get("/")) .andExpect(status().is3xxRedirection()) .andExpect(header().string("Location", "http://localhost/login"));

@Test @WithMockUser(username="craig", password="password", roles="READER") public void homePage_authenticatedUser() throws Exception {

...} 

@WithUserDetails("craig") public void homePage_authenticatedUser() throws Exception { Reader expectedReader = new Reader(); expectedReader.setUsername("craig"); expectedReader.setPassword("password"); expectedReader.setFullname("Craig Walls"); mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(view().name("readingList")) .andExpect(model().attribute("reader", samePropertyValuesAs(expectedReader))) .andExpect(model().attribute("books", hasSize(0))) }

测试运行在服务器里的Web应用程序 

@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration( classes=ReadingListApplication.class) @WebIntegrationTest public class SimpleWebTest { @Test(expected=HttpClientErrorException.class) public void pageNotFound() { try { RestTemplate rest = new RestTemplate(); rest.getForObject( "http://localhost:8080/bogusPage", String.class); fail("Should result in HTTP 404");

} catch (HttpClientErrorException e) {assertEquals(HttpStatus.NOT_FOUND, e.getStatusCode());throw e;

}}

虽然这个测试非常简单,但足以演示如何使用@WebIntegrationTest在服务器里启动应用程序。 

Spring Boot在随机选择的端口上启动服务器很方便。一种办法是将server.port属性设置为0,让Spring Boot选择一个随机的可用端口。@WebIntegrationTestvalue属性接受一个String数组,数组中的每项都是键值对,形如name=value,用来设置测试中使用的属性。要设置server.port,你可以这样做:

@WebIntegrationTest(value={"server.port=0"}) 另外,因为只要设置一个属性,所以还能有更简单的形式:

@WebIntegrationTest("server.port=0") 

通过value属性来设置属性通常还算方便。但@WebIntegrationTest还提供了一个randomPort属性,更明确地表示让服务器在随机端口上启动。你可以将randomPort设置为true,启用随机端口:

@WebIntegrationTest(randomPort=true)

既然我们在随机端口上启动了服务器,就需要在发起Web请求时确保使用正确的端口。此时的getForObject()方法在URL里硬编码了8080端口。如果端口是随机选择的,那在构造请求时又该怎么确定正确的端口呢?

首先,我们需要以实例变量的形式注入选中的端口。为了方便,Spring Bootlocal.server.port的值设置为了选中的端口。我们只需使用Spring@Value注解将其注入即可:

@Value("${local.server.port}") private int port;

有了端口之后,只需对getForObject()稍作修改,使用这个port就好了:rest.getForObject(

"http://localhost:{port}/bogusPage", String.class, port);这里我们在URL里把硬编码的8080改为{port}占位符。在getForObject()调用里把port

属性作为最后一个参数传入,就能确保该占位符被替换为注入port的值了 

Spring Boot里使用Selenium测试的模板 

@RunWith(SpringJUnit4ClassRunner.class) 

@SpringApplicationConfiguration( classes=ReadingListApplication.class) @WebIntegrationTest(randomPort=true) public class ServerWebTests { private static FirefoxDriver browser; @Value("${local.server.port}") private int port; @BeforeClass public static void openBrowser() { browser = new FirefoxDriver(); browser.manage().timeouts()

1

2

3

4

5

6

7

8

.implicitlyWait(10, TimeUnit.SECONDS);

配置Firefox驱动

4.3

注入端口号

启动

}

@AfterClass public static void closeBrowser() { browser.quit(); }

转载请注明原文地址: https://www.6miu.com/read-72633.html

最新回复(0)