废话不多说直接上教程
导包
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.2</version>
<scope>test</scope>
</dependency>
测试目标
class CustomerProjectDetail {
@Autowired
private labelInfoMapper ;
public List<String> getNames() {
return labelInfoMapper.selectCommonPlanByProject(null,"customer");
}
}
测试类
//加入mock依赖,没有这个注解无法mock
@ExtendWith(MockitoExtension.class)
public class TestDifferentProjectService {
//mock依赖对象
@Mock
LabelInfoMapper labelInfoMapper ;
//将mock的依赖对象注入到需要测试的对象中
@InjectMocks
private CustomerProjectDetail customerProjectDetail;
//编写测试方法
@Test
public void testGetNames(){
/**
* mock方法selectCommonPlanByProject的行为(可以理解为当测试对象需要调用这个方法的时候同时参数和下面
* 模仿的一样就返回null,这里的null可以是其他数据,可以更换为你想要它返回的数据),y一个方法可以模仿多种
* 情况,多种情况再写几个when就行。
*/
when(labelInfoMapper.selectCommonPlanByProject(null,"customer")).thenReturn(null);
CustomerProjectDetail differentProjectService = new CustomerProjectDetail();
List<String> names = differentProjectService.getNames();
//断言判断结果是否正确,断言类中有很多种方法,此处只列出一种
Assertions.assertEquals(1, names.size());
Assertions.assertEquals(names.get(0), "customer");
}```