目录介绍JUnit4和JUnit5的区别忽略测试用例执行RunWith配置@Before、@BeforeClass、@After、@AfterClass被替换开发环境示例介绍Spring启动2.2。版本0开始引入JUnit5作为默认的单元测试库。在SpringBoot2.2.0之前,spring-boot-starter-test包含了JUnit4的依赖,在SpringBoot2.2.0之后,被JunitJupiter取代。JUnit4和JUnit5的区别1.忽略测试用例执行JUnit4:@Test@IgnorepublicvoidtestMethod(){//...}JUnit5:@Test@Disabled("explanation")publicvoidtestMethod(){//...}2。RunWith配置JUnit4:@RunWith(SpringRunner.class)@SpringBootTestpublicclassApplicationTests{@TestpublicvoidcontextLoads(){}}JUnit5:@ExtendWith(SpringExtension.class)@SpringBootTestpublicclassApplicationTests{@TestpublicvoidcontextLoads(){}}3.@Before,@BeforeClass,@After、@AfterClass替换为@BeforeEach替换为@Before@BeforeAll替换为@BeforeClass@AfterEach替换为@After@AfterAll替换为@AfterClass开发环境JDK8示例1.创建一个SpringBoot项目。2、添加spring-boot-starter-web依赖,最终的pom.xml如下。4.0.0org.springframework.bootspring-boot-starter-parent<版本>2.2.6.RELEASEtutorial.spring.bootspring-boot-junit50.0.1-SNAPSHOTspring-boot-junit5DemoprojectforSpringBootUnitTestwithJUnit51.8org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-启动器测试测试org.junit.vintagejunit-vintage-engineorg.springframework.bootspring-boot-maven-plugin3.工程创建好之后自动生成了一个测试类packagetutorial.spring.boot.junit5;importorg.junit.jupiter.api.Test;importorg.springframework.boot.test.context.SpringBootTest;@SpringBootTestclassSpringBootJunit5ApplicationTests{@TestvoidcontextLoads(){}}该测试类用于检查应用上下文能否正常启动。@SpringBootTest注释告诉SpringBoot查找用@SpringBootApplication注释的主配置类,并使用它来启动Spring应用程序上下文。Java友公众号回复“后端面试”,送你Java面试题集4.补充待测应用逻辑代码4.1。定义Service层接口packagetutorial.spring.boot.junit5.service;);}4.2。定义Controller层包tutorial.spring.boot.junit5.controller;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind。annotation.RestController;importtutorial.spring.boot.junit5.service.HelloService;@RestControllerpublicclassHelloController{privatefinalHelloServicehelloService;publicHelloController(HelloServicehelloService){this.helloService=helloService;}@GetMapping("/hello/{name}")publicStringhello(@PathVariable("name")Stringname){returnhelloService.hello(name);}}4.3。定义Service层实现packagetutorial.spring.boot.junit5.service.impl;importorg.springframework.stereotype.Service;importtutorial.spring.boot.junit5。service.HelloService;@ServicepublicclassHelloServiceImplementsHelloService{@OverridepublicStringhello(Stringname){return"Hello,"+name;}}5.编写用于发送HTTP请求的单元测试packagetutorial.spring.boot.junit5;importorg.assertj.core.api.Assertions;importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context。SpringBootTest;importorg.springframework.boot.test.web.client.TestRestTemplate;importorg.springframework.boot.web.server.LocalServerPort;@SpringBootTest(webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT)publicclassHttpRequestTest{@LocalServerPortprivateintport;@AutowiredprivateTestRestTemplaterestTemplatetest;@Hello(public){StringrequestResult=this.restTemplate.getForObject("http://127.0.0.1:"+port+"/hello/spring",String.class);Assertions.assertThat(requestResult).contains("Hello,spring");}}描述:webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT使用本地随机端口启动服务;@LocalServerPort等价于@Value("${local.server.port}");配置好webEnvironment后,SpringBoot会自动提供一个TestRestTemplate实例,可用于发送HTTP请求除了使用TestRestTemplate实例发送HTTP请求外,还可以使用org.springframework.test.web.servlet.MockMvc来完成类似的功能。代码如下:packagetutorial.spring.boot.junit5.controller;importorg.assertj.core.api.Assertions;importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.test.web.servlet.MockMvc;importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;importorg.springframework.test.web.servlet.result.MockMvcResultHandlers;importorg.springframework.test.web.servlet。结果.MockMvcResultMatchers;@SpringBootTest@AutoConfigureMockMvcpublicclassHelloControllerTest{@AutowiredprivateHelloControllerhelloController;@AutowiredprivateMockMvcmockMvc;@TestpublicvoidtestNotNull(){Assertions.assertThat(helloController).isNotNull();}@TestpublicvoidHrowtestn{this.mockMvc.perform(MockMvcRequestBuilders.get("/hello/spring")).andDo(MockMvcResultHandlers.print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().string("Hello,spring"));}}上面的测试方法属于整体测试,即启动所有的applicationcontext,也有分层的测试方法,比如只测试Controller6层.分层测试。packagetutorial.spring.boot.junit5.controller;importorg.assertj.core.api.Assertions;importorg.junit.jupiter.api.Test;importorg.mockito.Mockito;importorg.springframework.beans.factory.annotation.Autowired;importorg。springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;importorg.springframework.boot.test.mock.mockito.MockBean;importorg.springframework.test.web.servlet.MockMvc;importorg.springframework.test.web.servlet。request.MockMvcRequestBuilders;importorg.springframework.test.web.servlet.result.MockMvcResultHandlers;importorg.springframework.test.web.servlet.result.MockMvcResultMatchers;importtutorial.spring.boot.junit5.service.HelloService;@WebMvcTestpublicclassHelloControllerTest{@AutowiredprivateHelloControllerhelloController;@AutowiredprivateMockMvcmockMvc;@MockBeanprivateHelloServicehelloService;@TestpublicvoidtestNotNull(){Assertions.assertThat(helloController).isNotNull();}@TestpublicvoidtestHello()throwsException{Mockito.when(helloService.hello(Mockito.anyString())).thenReturn("Mockhello");this.mockMvc.perform(MockMvcRequestBuilders.get("/hello/spring")).andDo(MockMvcResultHandlers.print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().string("Mockhello"));}}说明:@WebMvcTest注解告诉SpringBoot只实例化Controller层,不实例化整体上下文,You可以进一步指定只实例化Controller层的一个实例:@WebMvcTest(HelloController.class);因为只实例化了Controller层,需要通过@MockBean创建依赖的Service层实例,通过Mockito方法指定Mock特定情况下调用该方法时Service层实例的返回结果