SpringBoot单元测试

 

一 普通测试类

当有一个测试方法的时候,直接运行。

要在方法前后做事情,可以用before或者after。

假如有多个方法运行,则可以选择类进行运行。

 1 @RunWith(SpringRunner.class)
 2 @SpringBootTest
 3 public class TestApplicationTests {
 4  5  6     @Test
 7     public void testOne(){
 8         System.out.println("test hello 1");
 9         TestCase.assertEquals(1, 1);
10         
11     }
12     
13     @Test
14     public void testTwo(){
15         System.out.println("test hello 2");
16         TestCase.assertEquals(1, 1);
17         
18     }
19     
20     
21     
22     
23     @Before
24     public void testBefore(){
25         System.out.println("before");
26     }
27     
28     
29     
30     @After
31     public void testAfter(){
32         System.out.println("after");
33     }
34 35 }

 

测试结果:

2019-10-28 21:17:25.466  INFO 18872 --- [           main] com.example.demo.TestApplicationTests    : Started TestApplicationTests in 1.131 seconds (JVM running for 5.525)
before
test hello 1
after
before
test hello 2
after
​

 

二 MockMvc

1 perform方法其实只是为了构建一个请求,并且返回ResultActions实例,该实例则是可以获取到请求的返回内容。

2 MockMvcRequestBuilders该抽象类则是可以构建多种请求方式,如:PostGetPutDelete等常用的请求方式,其中参数则是我们需要请求的本项目的相对路径,/则是项目请求的根路径。

3 param方法用于在发送请求时携带参数,当然除了该方法还有很多其他的方法,大家可以根据实际请求情况选择调用。

4 andReturn方法则是在发送请求后需要获取放回时调用,该方法返回MvcResult对象,该对象可以获取到返回的视图名称、返回的Response状态、获取拦截请求的拦截器集合等。

5 我们在这里就是使用到了第4步内的MvcResult对象实例获取的MockHttpServletResponse对象从而才得到的Status状态码。

6 同样也是使用MvcResult实例获取的MockHttpServletResponse对象从而得到的请求返回的字符串内容。【可以查看rest返回的json数据】

7 使用Junit内部验证类Assert判断返回的状态码是否正常为200

8 判断返回的字符串是否与我们预计的一样。

要测试 Spring MVC 控制器是否正常工作,您可以使用@WebMvcTest annotation。 @WebMvcTest将 auto-configure Spring MVC 基础架构并将扫描的 beans 限制为@Controller@ControllerAdvice@JsonComponentFilterWebMvcConfigurerHandlerMethodArgumentResolver。使用此 annotation 时,不会扫描常规@Component beans。

@WebMvcTest通常仅限于一个控制器,并与@MockBean结合使用。

@WebMvcTest也 auto-configures MockMvc。 Mock MVC 提供了一种快速测试 MVC 控制器的强大方法,无需启动完整的 HTTP 服务器。

您也可以通过@AutoConfigureMockMvc注释非@WebMvcTest(e.g. SpringBootTest)auto-configure MockMvc

 1 import org.junit.*;
 2 import org.junit.runner.*;
 3 import org.springframework.beans.factory.annotation.*;
 4 import org.springframework.boot.test.autoconfigure.web.servlet.*;
 5 import org.springframework.boot.test.mock.mockito.*;
 6  7 import static org.assertj.core.api.Assertions.*;
 8 import static org.mockito.BDDMockito.*;
 9 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
10 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
11 12 @RunWith(SpringRunner.class)
13 @WebMvcTest(UserVehicleController.class)
14 public class MyControllerTests {
15 16     @Autowired
17     private MockMvc mvc;
18 19     @MockBean
20     private UserVehicleService userVehicleService;
21 22     @Test
23     public void testExample() throws Exception {
24         given(this.userVehicleService.getVehicleDetails("sboot"))
25                 .willReturn(new VehicleDetails("Honda", "Civic"));
26         this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN))
27                 .andExpect(status().isOk()).andExpect(content().string("Honda Civic"));
28     }
29 30 }

 

如果需要配置 auto-configuration 的元素(对于应用 servlet 过滤器的 example),可以使用@AutoConfigureMockMvc annotation 中的属性。

如果您使用 HtmlUnit 或 Selenium,auto-configuration 还将提供WebClient bean and/or a WebDriver bean。这是一个使用 HtmlUnit 的 example:

 1 import com.gargoylesoftware.htmlunit.*;
 2 import org.junit.*;
 3 import org.junit.runner.*;
 4 import org.springframework.beans.factory.annotation.*;
 5 import org.springframework.boot.test.autoconfigure.web.servlet.*;
 6 import org.springframework.boot.test.mock.mockito.*;
 7  8 import static org.assertj.core.api.Assertions.*;
 9 import static org.mockito.BDDMockito.*;
10 11 @RunWith(SpringRunner.class)
12 @WebMvcTest(UserVehicleController.class)
13 public class MyHtmlUnitTests {
14 15     @Autowired
16     private WebClient webClient;
17 18     @MockBean
19     private UserVehicleService userVehicleService;
20 21     @Test
22     public void testExample() throws Exception {
23         given(this.userVehicleService.getVehicleDetails("sboot"))
24                 .willReturn(new VehicleDetails("Honda", "Civic"));
25         HtmlPage page = this.webClient.getPage("/sboot/vehicle.html");
26         assertThat(page.getBody().getTextContent()).isEqualTo("Honda Civic");
27     }
28 29 }

默认情况下 Spring Boot 会将WebDriver beans 放在一个特殊的“范围”中,以确保在每次测试后退出驱动程序,并注入新实例。如果您不想要此行为,可以将@Scope("singleton")添加到WebDriver @Bean定义中。

`

测试

 1 @RunWith(SpringRunner.class)  //底层用junit  SpringJUnit4ClassRunner
 2 //@SpringBootTest(classes={TestApplicationTests.class}) //启动整个springboot工程
 3 //@AutoConfigureMockMvc 
 4 @WebMvcTest(TestController.class)
 5 public class MockMvcTestDemo {
 6  7     
 8     @Autowired
 9     private MockMvc mockMvc;
10     
11     
12     
13     @Test
14     public void apiTest() throws Exception {
15         
16         MvcResult mvcResult =  mockMvc.perform( MockMvcRequestBuilders.get("/test/hello") ).
17                 andExpect( MockMvcResultMatchers.status().isOk() ).andReturn();
18         int status = mvcResult.getResponse().getStatus();
19         System.out.println(status);
20         
21          String responseString = mockMvc.perform( MockMvcRequestBuilders.get("/test/hello") ).
22                 andExpect( MockMvcResultMatchers.status().isOk() ).andDo(print())         //打印出请求和相应的内容
23           .andReturn().getResponse().getContentAsString();
24          System.out.println(responseString);
25         
26     }
27     
28 }
29 @RestController
30 public class TestController {
31     
32     @RequestMapping("/test/hello")
33     public String test() {
34         return "hello";
35     }
36 37 }
38

 

结果:

2019-10-28 22:02:18.022  INFO 5736 --- [           main] com.example.demo.MockMvcTestDemo         : Started MockMvcTestDemo in 2.272 seconds (JVM running for 3.352)
200
​
MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /test/hello
       Parameters = {}
          Headers = []
             Body = <no character encoding set>
    Session Attrs = {}
​
Handler:
             Type = com.example.demo.web.TestController
           Method = public java.lang.String com.example.demo.web.TestController.test()
​
Async:
    Async started = false
     Async result = null
​
Resolved Exception:
             Type = null
​
ModelAndView:
        View name = null
             View = null
            Model = null
​
FlashMap:
       Attributes = null
​
MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"text/plain;charset=UTF-8", Content-Length:"5"]
     Content type = text/plain;charset=UTF-8
             Body = hello
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
hello

 

 

posted @ 2019-10-28 22:06  天宇轩-王  阅读(383)  评论(0编辑  收藏  举报