SpringBoot单元测试解读
作者:Exill
SpringBoot提供了基于JUnit5的测试工具,方便进行测试,默认导入相关依赖,创建测试类,使用断言(Assertions类)进行断言操作,支持参数化测试
SpringBoot提供一系列基于JUnit5的测试工具方便测试
1.导入
SpringBoot项目默认自动导入该依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
默认创建的测试类
@SpringBootTest //有这个注解才能使用SpringBoot容器bean //没有此注解就是普通JUnit5 class SpringSecurityApplicationTests { @Test void contextLoads() { } }
2.使用
@SpringBootTest class SpringBootTestsApplicationTests { @Resource//注入IOC中的bean PersonProperty person; @Test//测试方法 void contextLoads() { System.out.println(person); } @BeforeEach//每个测试方法开始前 void beforeEach(){ System.out.println("每个测试方法开始前"); } @AfterEach//每个测试方法结束后 void afterEach(){ System.out.println("每个测试方法结束后"); } @BeforeAll//测试开始 static void beforeAll(){ System.out.println("测试开始"); } @AfterAll//测试结束 static void afterAll(){ System.out.println("测试结束"); } }
3.断言使用(Assertions类)
@Test void checkResult(){ Integer age = person.getAge(); Assertions.assertEquals(18,age); }
4.参数化测试
@ParameterizedTest @ValueSource(strings = {"ab","cd","ef"}) void test1(String param){ System.out.println(param); }
@ParameterizedTest @MethodSource("paramForTest2") void test2(Map<String,String> param){ System.out.println(param); } static Stream<Map<String,String>> paramForTest2(){ Map<String,String> map1 = Map.of("a","a1","b","b1"); Map<String,String> map2 = Map.of("a","a2","b","b2"); return Stream.of(map1,map2); }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。