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); }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论