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 {
@Mock
private IOtherService otherService;
@InjectMocks
private ServiceImpl service;
@Test
public void xxxTest() {
//使用when对depdService方法进行模拟,使用eq、anyString对参数进行检验,使用threnReturn返回结果
when(otherService.doSomething(eq("参数"), anyString())).thenReturn("xxxx");
assertEquals("xxxx", service.doSomething("参数"));
verify(otherService).doSomething(eq("参数"), anyString());
//直接使用原始值
when(otherService.doSomething("参数1", "参数1aaa")).thenReturn("xxxx1");
assertEquals("xxxx1", service.doSomething("参数1"));
verify(otherService).doSomething("参数1", "参数1aaa");
clearInvocations(otherService);//清除之前的调用
assertNull(service.doSomething(""));
//检测未被调用
verifyNoInteractions(otherService);
}
}
其他服务类:
import org.springframework.beans.factory.annotation.Autowired;
public class ServiceImpl {
@Autowired
private IOtherService otherService;
public String doSomething(String param) {
if (param.isEmpty()) {
return null;
}
return otherService.doSomething(param, param + "aaa");
}
}
public interface IOtherService {
String doSomething(String param1, String param2);
}
常用Mockito功能参考
Mockito使用错误记录
参数检验时原始参数与检验参数混用
错误代码:
when(otherService.doSomething("参数", anyString())).thenReturn("xxxx1");
错误提示:
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
错误原因:方法参数未正确使用
正确代码:
when(otherService.doSomething(eq("参数"), anyString())).thenReturn("xxxx1");