现在的位置: 首页 > 编程语言 > 正文

SpringBoot2种单元测试方法解析

2020年02月13日 编程语言 ⁄ 共 5339字 ⁄ 字号 评论关闭

一 普通测试类

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

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

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

@RunWith(SpringRunner.class)@SpringBootTestpublic class TestApplicationTests { @Test public void testOne(){ System.out.println("test hello 1"); TestCase.assertEquals(1, 1); } @Test public void testTwo(){ System.out.println("test hello 2"); TestCase.assertEquals(1, 1); } @Before public void testBefore(){ System.out.println("before"); } @After public void testAfter(){ System.out.println("after"); }​}

测试结果:

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)beforetest hello 1afterbeforetest hello 2after

二 MockMvc

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

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

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,@JsonComponent,Filter,WebMvcConfigurer和HandlerMethodArgumentResolver。使用此 annotation 时,不会扫描常规@Component beans。

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

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

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

import org.junit.*;import org.junit.runner.*;import org.springframework.beans.factory.annotation.*;import org.springframework.boot.test.autoconfigure.web.servlet.*;import org.springframework.boot.test.mock.mockito.*;​import static org.assertj.core.api.Assertions.*;import static org.mockito.BDDMockito.*;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;​@RunWith(SpringRunner.class)@WebMvcTest(UserVehicleController.class)public class MyControllerTests {​ @Autowired private MockMvc mvc;​ @MockBean private UserVehicleService userVehicleService;​ @Test public void testExample() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")) .willReturn(new VehicleDetails("Honda", "Civic")); this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) .andExpect(status().isOk()).andExpect(content().string("Honda Civic")); }}

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

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

import com.gargoylesoftware.htmlunit.*;import org.junit.*;import org.junit.runner.*;import org.springframework.beans.factory.annotation.*;import org.springframework.boot.test.autoconfigure.web.servlet.*;import org.springframework.boot.test.mock.mockito.*;​import static org.assertj.core.api.Assertions.*;import static org.mockito.BDDMockito.*;​@RunWith(SpringRunner.class)@WebMvcTest(UserVehicleController.class)public class MyHtmlUnitTests {​ @Autowired private WebClient webClient;​ @MockBean private UserVehicleService userVehicleService;​ @Test public void testExample() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")) .willReturn(new VehicleDetails("Honda", "Civic")); HtmlPage page = this.webClient.getPage("/sboot/vehicle.html"); assertThat(page.getBody().getTextContent()).isEqualTo("Honda Civic"); }​}

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

测试

@RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner//@SpringBootTest(classes={TestApplicationTests.class}) //启动整个springboot工程//@AutoConfigureMockMvc @WebMvcTest(TestController.class)public class MockMvcTestDemo { @Autowired private MockMvc mockMvc; @Test public void apiTest() throws Exception { MvcResult mvcResult = mockMvc.perform( MockMvcRequestBuilders.get("/test/hello") ). andExpect( MockMvcResultMatchers.status().isOk() ).andReturn(); int status = mvcResult.getResponse().getStatus(); System.out.println(status); String responseString = mockMvc.perform( MockMvcRequestBuilders.get("/test/hello") ). andExpect( MockMvcResultMatchers.status().isOk() ).andDo(print()) //打印出请求和相应的内容 .andReturn().getResponse().getContentAsString(); System.out.println(responseString); } }@RestControllerpublic class TestController { @RequestMapping("/test/hello") public String test() { return "hello"; }​}​

结果:

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)​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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: SpringBoot2种单元测试方法解析

以上就上有关SpringBoot2种单元测试方法解析的相关介绍,要了解更多springboot,单元测试内容请登录学步园。

抱歉!评论已关闭.