单测入门案例:JUnit+Mockito
导入依赖
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.21.0</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.11</version>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>target/jacoco.exec</dataFile>
<outputDirectory>target/jacoco-ut</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.9.0</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.9.0</version>
</dependency>
具体实现
1.声明类
@RunWith(MockitoJUnitRunner.class)
public class UnitServiceImplTest {
//mock被单测的service
@InjectMocks
private UnitServiceImpl unitService;
//mock被单测的service里注入的其他bean
@Mock
private UserService userService;
//mock被单测的service里注入的其他bean
@Mock
private EsSearchStaffService esSearchStaffService;
//这里面写具体的单测方法
@Test
public void getUserInfoByYhtUserId(){
}
}
2.常量正常声明即可
String keyword = "秦";
List<String> userIdList = new ArrayList<>();
3.mock静态方法
MockedStatic<InvocationInfoProxy> invocationInfoProxyMockedStatic = Mockito.mockStatic(InvocationInfoProxy.class);
String userId = InvocationInfoProxy.getUserId();
4.mock外部调用、注入的service或者mapper
Mockito.when(userService.getUserList(yhtUserIdList)).thenReturn(new ArrayList<>());
Mockito.when(userMapper.getUserList(yhtUserIdList)).thenReturn(new ArrayList<>());
5.mock异常
//这里模拟异常时必须抛具体的异常,直接抛Exception的话mockito会异常
Mockito.when(userService.searchByUserIdsWithoutPower(userIdList, keyword)).thenThrow(new BusinessException());
6.mock异步方法
@Mock
ThreadPoolExecutor threadPoolExecutor;
@Test
public void getUserInfoByYhtUserId(){
//mock入参
List<String> userIdList = new ArrayList<>();
userIdList.add(1);
userIdList.add(2);
//调用被单测的方法里的异步逻辑的run方法
Mockito.doAnswer(
(InvocationOnMock invocation) -> {
((Runnable) invocation.getArguments()[0]).run();
return null;
}
).when(threadPoolExecutor).execute(Mockito.any(Runnable.class));
//执行单测方法
unitService.getUserInfo(userIdList );
}
常用命令
1、执行单测 mvn test
2、生成单测UI报告mvn jacoco:report
3、在idea执行单测方法看单测覆盖率