前言:
开发过程中经常需要写单元测试,记录一下单元测试spring-boot-starter-test+junit5的使用
引入内容:
引用jar包
<!-- SpringBoot测试类依赖 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>
<!-- junit -->
<dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>5.9.2</version><scope>test</scope>
</dependency>
注入service\mapper代码测试:
可以对局部函数、方法进行调用测试
import java.util.*;
import java.util.stream.Collectors;@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class DServerLocalApplicationTests {@AutowiredAService aService;@Autowiredprivate AMapper aMapper;@Autowiredprivate BMapper bMapper;@Testvoid test() {List<A> a= aMapper.selectList(null);List<B> b = bMapper.selectList(null); ...}
}
测试restful接口:
可以对API调用进行模拟测试
/*** @author CH* @version 1.0 单元测试模板案例* @data 2023/6/6 14:12*/
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class TestTemplateTests {// MockMvc是Spring提供的专用于测试Controller类private MockMvc mockMvc;@Autowiredprivate WebApplicationContext wac;@Beforepublic void setup() {// 初始化MockMvc对象;this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();}@Beforepublic void init() {log.info("开始测试...");}@Afterpublic void after() {log.info("测试结束...");}/**** 加@Transactional可以对单元测试执行的结果进行回滚,不会产生脏数据*/@Transactional@Testpublic void getTest() throws Exception {ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders// URL =>注意:在测试类中,不需要将根路径写进去 ,还有很多调用方式post\put\delete.get("/appAssets/assetsTest")// 参数格式.contentType(MediaType.APPLICATION_JSON)// 传参格式很多
// .content(JSONObject.toJSONString(""))
// .header()
// .param());MvcResult mvcResult =resultActions// 接口调用状态.andExpect(MockMvcResultMatchers.status().isOk())// 打印结果数据.andDo(MockMvcResultHandlers.print()).andReturn();// 取到结果进行断言Result result = JSON.parseObject(mvcResult.getResponse().getContentAsString(), Result.class);// 对结果进行断言Assertions.assertEquals("操作成功", result.getMessage());Assertions.assertEquals(200, result.getStatus());}}