天天看点

springboot单元测试mock依赖的类

引入包,测试版本:<powermock.version>1.7.1</powermock.version>

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito2</artifactId>
    <version>${powermock.version}</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>${powermock.version}</version>
    <scope>test</scope>
</dependency>
           
//aService类的findStudyInfoById方法内部实现,调用了bDao的方法,
//单元测试只需关心aService当前层的正确性,bDao的正确性由它自己的单元测试保证,
//所以需要模拟一个假的bDao场景,来配合完成aService的单元测试
public class MockTest {
 
    //注入要测试类,注意这里注入写实现类,不能写接口注入
    @InjectMocks
    private AServiceImpl aService;
 
    //mock这个类,帮助测试aService,而不测试实际的bDao
    @Mock
    private BDao bDao;
 
    //初始化测试数据
    @Before
    public void initMock() {
        MockitoAnnotations.initMocks(this);
        Student student = new Student;
        student.setName("测试");
        student.setId(1);
        //初始化mock类的场景,如果传入一个int,返回自己mock的student数据
        when(bDao.findStudyInfoById(anyInt())).thenReturn(student);
    }
 
    @Test
    public void findStudyInfoById() throws Exception {
        List<Student> students = aService.findStudyInfoById(1);
        Assert.assertTrue(rstudents.size()==1);
    }
 
}
           

继续阅读