SpringBoot2 + Junit5测试案例

发表于:2020-6-10 10:39  作者:努力做一个伪程序员   来源:博客园

字体: | 上一篇 | 下一篇 |我要投稿 | 推荐标签: Junit5 白盒测试工具

  使用最新的springboot的版本,使用的是junit5版本,现在很多都是使用junit4的测试,这里使用Junit5来试验.junit4和junit5两个版本差别比较大
  
  使用ideal构建springboot项目,pom.xml(部分)如下:
   <?xmlversion="1.0"encoding="UTF-8"?>
  <projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.2.6.RELEASE</version>
  <relativePath/><!--lookupparentfromrepository-->
  </parent>
  <groupId>com.test</groupId>
  <artifactId>demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>demo</name>
  <description>DemoprojectforSpringBoot</description>
  <properties>
  <java.version>1.8</java.version>
  </properties>
  <dependencies>
  <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  </dependency><!--加入下面的引入,可以使用junit5的版本来测试;如果想用junit4的测试,把exclusioins去除-->
  <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
  <exclusions>
  <exclusion>
  <groupId>org.junit.vintage</groupId>
  <artifactId>junit-vintage-engine</artifactId>
  </exclusion>
  </exclusions>
  </dependency>
  </dependencies>
  </project>
   建立一个controller
   packagecom.test.demo.controller;
  importorg.slf4j.Logger;
  importorg.slf4j.LoggerFactory;
  importorg.springframework.beans.factory.annotation.Autowired;
  importorg.springframework.stereotype.Controller;
  importorg.springframework.web.bind.annotation.*;
  @Controller
  @RequestMapping("/index")
  publicclassIndexController{
  privatestaticfinalLoggerLOG=LoggerFactory.getLogger(IndexController.class);
  @RequestMapping(value="/getData")
  @ResponseBody
  publicStringgetData(@RequestParam(value="searchPhrase",required=false)StringsearchPhrase){
  Stringstatus="{\"status\":\"200\",\"searchPhrase\":\""+searchPhrase+"\"}";
  returnstatus;
  }
  }
   建立一个测试类:
   packagecom.test.demo;
  importcom.test.demo.controller.IndexController;
  importorg.junit.jupiter.api.*;//注意这里,这是junit5引入的;junit4引入的是org.junit.Test这样类似的包
  importorg.slf4j.Logger;
  importorg.slf4j.LoggerFactory;
  importorg.springframework.beans.factory.annotation.Autowired;
  importorg.springframework.boot.test.context.SpringBootTest;
  importorg.springframework.http.MediaType;
  importorg.springframework.test.web.servlet.MockMvc;
  importorg.springframework.test.web.servlet.MvcResult;
  importorg.springframework.test.web.servlet.RequestBuilder;
  importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;
  importorg.springframework.test.web.servlet.result.MockMvcResultHandlers;
  importorg.springframework.test.web.servlet.result.MockMvcResultMatchers;
  importorg.springframework.test.web.servlet.setup.MockMvcBuilders;
  importorg.springframework.web.context.WebApplicationContext;
  //这里只写SpringBootTest这个注解;如果是junit4的话,就要加上@RunWith(SpringRunner.class)
  @SpringBootTest
  classDemoApplicationTests{
  privatestaticfinalLoggerLOG=LoggerFactory.getLogger(DemoApplicationTests.class);
  privateMockMvcmockMvc;
  @Autowired
  privateWebApplicationContextwebApplicationContext;
  @Test
  voidcontextLoads(){
  }
  @BeforeAll
  publicstaticvoidbeforeAll(){
  LOG.info("beforeAll");
  }
  @BeforeEach
  publicvoidbeforeEach(){
  LOG.info("beforeEach");//mockMvc=MockMvcBuilders.standaloneSetup(newIndexController()).build();
  mockMvc=MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
  }
  @AfterEach
  publicvoidafterEach(){
  LOG.info("afterEach");
  }
  @AfterAll
  publicstaticvoidafterAll(){
  LOG.info("afterAll");
  }
  @Test
  publicvoidtestTwo()throwsException{
  RequestBuilderrequest=MockMvcRequestBuilders.get("/index/getData")
  .param("searchPhrase","ABC")//传参
  .accept(MediaType.APPLICATION_JSON)
  .contentType(MediaType.APPLICATION_JSON);//请求类型JSON
  MvcResultmvcResult=mockMvc.perform(request)
  .andExpect(MockMvcResultMatchers.status().isOk())//期望的结果状态200
  .andDo(MockMvcResultHandlers.print())//添加ResultHandler结果处理器,比如调试时打印结果(print方法)到控制台
  .andReturn();//返回验证成功后的MvcResult;用于自定义验证/下一步的异步处理;
  intstatus=mvcResult.getResponse().getStatus();//得到返回代码
  Stringcontent=mvcResult.getResponse().getContentAsString();//得到返回结果
  LOG.info("status:"+status+",content:"+content);
  }
  }
   最后进行测试:
  进入自己的目录,这里我是通过命令运行的,也可以通过其他方式运行(如ide的环境)
  cdxxx/Demo>mvntest
  测试结果如下:
   2020-04-1113:04:49.920[main]INFOcom.test.demo.DemoApplicationTests-beforeAll
  2020-04-1113:04:55.239[main]com.test.demo.DemoApplicationTests:beforeEach
  MockHttpServletRequest:
  HTTPMethod=GET
  RequestURI=/index/getData
  Parameters={searchPhrase=[ABC]}
  Headers=[Content-Type:"application/json",Accept:"application/json"]
  Body=<nocharacterencodingset>
  SessionAttrs={}
  Handler:
  Type=com.test.demo.controller.IndexController
  Method=com.test.demo.controller.IndexController#getData(String)
  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:"application/json",Content-Length:"42"]
  Contenttype=application/json
  Body={"status":"200","searchPhrase":"ABC"}
  ForwardedURL=null
  RedirectedURL=null
  Cookies=[]
  2020-04-1113:04:55.395INFO13164---[main]com.test.demo.DemoApplicationTests:status:200,content:{"status":"200","searchPhrase":"ABC"}
  2020-04-1113:04:56.002INFO13164---[main]com.test.demo.DemoApplicationTests:afterEach
  2020-04-1113:04:56.009INFO13164---[main]com.test.demo.DemoApplicationTests:afterAll
   这里可以看到返回的结果status:200,content:{"status":"200","searchPhrase":"ABC"}
  其中传入的参数是ABC

      本文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理

评 论

论坛新帖



建议使用IE 6.0以上浏览器,800×600以上分辨率,法律顾问:上海信义律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2021, 沪ICP备05003035号
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪公网安备 31010102002173号

51Testing官方微信

51Testing官方微博

扫一扫 测试知识全知道