SpringBoot2种单元测试方法解析
一普通测试类
当有一个测试方法的时候,直接运行。
要在方法前后做事情,可以用before或者after。
假如有多个方法运行,则可以选择类进行运行。
@RunWith(SpringRunner.class)
@SpringBootTest
publicclassTestApplicationTests{
@Test
publicvoidtestOne(){
System.out.println("testhello1");
TestCase.assertEquals(1,1);
}
@Test
publicvoidtestTwo(){
System.out.println("testhello2");
TestCase.assertEquals(1,1);
}
@Before
publicvoidtestBefore(){
System.out.println("before");
}
@After
publicvoidtestAfter(){
System.out.println("after");
}
}
测试结果:
2019-10-2821:17:25.466INFO18872---[main]com.example.demo.TestApplicationTests:StartedTestApplicationTestsin1.131seconds(JVMrunningfor5.525) before testhello1 after before testhello2 after
二MockMvc
1perform方法其实只是为了构建一个请求,并且返回ResultActions实例,该实例则是可以获取到请求的返回内容。
2MockMvcRequestBuilders该抽象类则是可以构建多种请求方式,如:Post、Get、Put、Delete等常用的请求方式,其中参数则是我们需要请求的本项目的相对路径,/则是项目请求的根路径。
3param方法用于在发送请求时携带参数,当然除了该方法还有很多其他的方法,大家可以根据实际请求情况选择调用。
4andReturn方法则是在发送请求后需要获取放回时调用,该方法返回MvcResult对象,该对象可以获取到返回的视图名称、返回的Response状态、获取拦截请求的拦截器集合等。
5我们在这里就是使用到了第4步内的MvcResult对象实例获取的MockHttpServletResponse对象从而才得到的Status状态码。
6同样也是使用MvcResult实例获取的MockHttpServletResponse对象从而得到的请求返回的字符串内容。【可以查看rest返回的json数据】
7使用Junit内部验证类Assert判断返回的状态码是否正常为200
8判断返回的字符串是否与我们预计的一样。
要测试SpringMVC控制器是否正常工作,您可以使用@WebMvcTestannotation。@WebMvcTest将auto-configureSpringMVC基础架构并将扫描的beans限制为@Controller,@ControllerAdvice,@JsonComponent,Filter,WebMvcConfigurer和HandlerMethodArgumentResolver。使用此annotation时,不会扫描常规@Componentbeans。
@WebMvcTest通常仅限于一个控制器,并与@MockBean结合使用。
@WebMvcTest也auto-configuresMockMvc。MockMVC提供了一种快速测试MVC控制器的强大方法,无需启动完整的HTTP服务器。
您也可以通过@AutoConfigureMockMvc注释非@WebMvcTest(e.g.SpringBootTest)auto-configureMockMvc。
importorg.junit.*;
importorg.junit.runner.*;
importorg.springframework.beans.factory.annotation.*;
importorg.springframework.boot.test.autoconfigure.web.servlet.*;
importorg.springframework.boot.test.mock.mockito.*;
importstaticorg.assertj.core.api.Assertions.*;
importstaticorg.mockito.BDDMockito.*;
importstaticorg.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
importstaticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringRunner.class)
@WebMvcTest(UserVehicleController.class)
publicclassMyControllerTests{
@Autowired
privateMockMvcmvc;
@MockBean
privateUserVehicleServiceuserVehicleService;
@Test
publicvoidtestExample()throwsException{
given(this.userVehicleService.getVehicleDetails("sboot"))
.willReturn(newVehicleDetails("Honda","Civic"));
this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk()).andExpect(content().string("HondaCivic"));
}
}
如果需要配置auto-configuration的元素(对于应用servlet过滤器的example),可以使用@AutoConfigureMockMvcannotation中的属性。
如果您使用HtmlUnit或Selenium,auto-configuration还将提供WebClientbeanand/oraWebDriverbean。这是一个使用HtmlUnit的example:
importcom.gargoylesoftware.htmlunit.*;
importorg.junit.*;
importorg.junit.runner.*;
importorg.springframework.beans.factory.annotation.*;
importorg.springframework.boot.test.autoconfigure.web.servlet.*;
importorg.springframework.boot.test.mock.mockito.*;
importstaticorg.assertj.core.api.Assertions.*;
importstaticorg.mockito.BDDMockito.*;
@RunWith(SpringRunner.class)
@WebMvcTest(UserVehicleController.class)
publicclassMyHtmlUnitTests{
@Autowired
privateWebClientwebClient;
@MockBean
privateUserVehicleServiceuserVehicleService;
@Test
publicvoidtestExample()throwsException{
given(this.userVehicleService.getVehicleDetails("sboot"))
.willReturn(newVehicleDetails("Honda","Civic"));
HtmlPagepage=this.webClient.getPage("/sboot/vehicle.html");
assertThat(page.getBody().getTextContent()).isEqualTo("HondaCivic");
}
}
默认情况下SpringBoot会将WebDriverbeans放在一个特殊的“范围”中,以确保在每次测试后退出驱动程序,并注入新实例。如果您不想要此行为,可以将@Scope("singleton")添加到WebDriver@Bean定义中。
测试
@RunWith(SpringRunner.class)//底层用junitSpringJUnit4ClassRunner
//@SpringBootTest(classes={TestApplicationTests.class})//启动整个springboot工程
//@AutoConfigureMockMvc
@WebMvcTest(TestController.class)
publicclassMockMvcTestDemo{
@Autowired
privateMockMvcmockMvc;
@Test
publicvoidapiTest()throwsException{
MvcResultmvcResult=mockMvc.perform(MockMvcRequestBuilders.get("/test/hello")).
andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
intstatus=mvcResult.getResponse().getStatus();
System.out.println(status);
StringresponseString=mockMvc.perform(MockMvcRequestBuilders.get("/test/hello")).
andExpect(MockMvcResultMatchers.status().isOk()).andDo(print())//打印出请求和相应的内容
.andReturn().getResponse().getContentAsString();
System.out.println(responseString);
}
}
@RestController
publicclassTestController{
@RequestMapping("/test/hello")
publicStringtest(){
return"hello";
}
}
结果:
2019-10-2822:02:18.022INFO5736---[main]com.example.demo.MockMvcTestDemo:StartedMockMvcTestDemoin2.272seconds(JVMrunningfor3.352)
MockHttpServletRequest:
HTTPMethod=GET
RequestURI=/test/hello
Parameters={}
Headers=[]
Body=
SessionAttrs={}
Handler:
Type=com.example.demo.web.TestController
Method=publicjava.lang.Stringcom.example.demo.web.TestController.test()
Async:
Asyncstarted=false
Asyncresult=null
ResolvedException:
Type=null
ModelAndView:
Viewname=null
View=null
Model=null
FlashMap:
Attributes=null
MockHttpServletResponse:
Status=200
Errormessage=null
Headers=[Content-Type:"text/plain;charset=UTF-8",Content-Length:"5"]
Contenttype=text/plain;charset=UTF-8
Body=hello
ForwardedURL=null
RedirectedURL=null
Cookies=[]
hello
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。