目录
分类
依赖
单元测试
功能测试
切面测试
单元测试
面向方法,测试成本较大
切片测试
面向难以测试的边界功能。@RunWith @WebMvcTest等
功能测试
面向整个业务功能,推荐使用。@RunWith @SpringBootTest等
org.springframework.boot
spring-boot-starter-test
test
包含的依赖有
JUnit
Spring Test & SpringBoot Test
AssertJ: 流式断言
Hamcrest
Mockito:mock框架
JSONassert:为JSON提供断言
JsonPath:为JSON提供XPATH功能
JUnit4
@RunWith(SpringRunner.class)
@SpringBootTest
class PhysicsExperimentApplicationTests {
@Autowired
private ExperimentMapper experimentMapper;
@Test
public void testSelectAllE(){
List experiments = experimentMapper.selectList(new QueryWrapper());
for(Experiment e : experiments){
System.out.println(e);
}
}
}
JUnit5
@SpringBootTest
class PhysicsExperimentApplicationTests {
@Autowired
private ExperimentMapper experimentMapper;
@Test
void testSelectAllE(){
List experiments = experimentMapper.selectList(new QueryWrapper());
for(Experiment e : experiments){
System.out.println(e);
}
}
}
首先我们需要弄白自己SpringBoot的版本
在SpringBoot2.2.0以前是JUnit4,在SpringBoot之后是JUnit5。
JUnit4中当我们需要自动装配时(@Autowired),需要添加
@RunWith(SpringRunner.class)
将Bean载入,否则会报空指针异常。
JUnit5 不需要添加@RunWith注释,原因如下:
如果您使用的是JUnit 5,则不需要添加等效的代码
@Wxtendwith (SpringExtension.class)作为@Springboottest和其他@..测试注释已经用它做了注解。
同时,对于Junit4而言,所有的测试方法应当是public声明的,而Junit5不用。
@SpringBootTest注解会自动检索程序的配置文件,检索顺序为从当前包逐级向上找被@SpringBootApplication 或者 @SpringBootConfiguration注释的类。
可以采用Mockito
(8条消息) 【Mockito】SpringBoot中的应用笔记_何处是归途、的博客-CSDN博客
未学
来源:
SpringBoot Test及注解详解 - codedot - 博客园 (cnblogs.com)
spring boot的测试类要不要加@RunWith(SpringJUnit4ClassRunner.class)?-CSDN社区
(10条消息) SpringBoot测试类不需要加@RunWith?_不加runwith_春盏77的博客-CSDN博客