前言
作为程序员为了提前发现代码bug,优化代码; 通常我们写完某个功能模块代码后都需要写单元测试对代码块进行测试(特别是敏捷开发中);Java项目最常用的单元测试框架即为Junit(目前最新版本为Junit5),SpringBoot本身也整合了该框架。在写单元测试时代码块中的调到第三方接口方法或涉及数据库操作的接口方法一般都需要mock掉(测试中叫打测试桩)。目前在 Java 中主流的 Mock 测试框架有 Mockito、JMock、EasyMock,Mockito 框架是SpringBoot 目前内建的 框架。本文主要介绍Junit5+Mockito在SpringBoot项目写单元测试的使用。
maven依赖
Mockito,Junit在SpringBoot 内部已依赖只需引入spring-boot-starter-test即可。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
Junit5基本使用
基本注解:
类注解:
@TestInstance(Lifecycle.PER_CLASS)注解
如果您希望JUnit Jupiter在同一个测试实例上执行所有测试方法,只需使用@TestInstance(Lifecycle.PER_CLASS)注释您的测试类。使用此模式时,每个测试类将创建一个新的测试实例。如果没使用@TestInstance(Lifecycle.PER_CLASS)注解,使用@BeforeAll和@AfterAll注解必须在static静态方法上使用。
- TestInstance.Lifecycle.PER_CLASS:每个测试类将创建一个新的测试实例。
- TestInstance.Lifecycle.PER_METHOD:将为每种测试方法,测试工厂方法或测试模板方法创建一个新的测试实例。此模式类似于JUnit版本1至4中的行为。
@ExtendWith(MockitoExtension.class)注解
用在springboot项目中,涉及spring的单元测试需要使用@ExtendWith(SpringExtension.class)注解,可以mock spring bean。不涉及spring时使用@ExtendWith(MockitoExtension.class)。
@ExtendWith(SpringExtension.class)注解在Spring boot 2.1.x需要配合