Springboot中使用Junit5和Mockito
如果不关心Junit5和Mockito的,直接看使用方法
使用方法
环境配置
使用的是springboot版本为2.3.3.RELEASE,spring-boot-starter-test自带了 mockito-core,因此只需要在pom.xml中引入spring-boot-starter-test,即可使用junit5(即Junit Jupiter):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
用例配置
通过使用@ExtendWith(MockitoExtension.class)后,相当于在@BeforeEach调用MockitoAnnotations.initMocks(this),
Mockito使用
然后即可在测试类中使用注解@InjectMocks和@Mock注入对象,在方法中使用常用Mockito功能进行测试了
测试类:
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class ServiceImplTest