Mockito 可以mock 一个接口或类,创建一个类或接口的mock实例是指这个mock实例拥有这个类或接口的所有方法,并且给这些方法以最基本的实现
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.List;
import org.junit.Test;
public class MockitoTest {
@Test
public void test() throws Exception {
// 使用mock()方法 创建List接口的mock实例
List list = mock(List.class);
list.add("xx");
verify(list, times(1)).add("xx");
verify(list, times(0)).add("y");
}
}
在SpringBoot Test中,@MockBean注解可以创建接口的mock实例,添加mock对象到 Spring ApplicationContext中。例如StudentServiceImpl类需要依赖StudentRepository接口,那么在测试StudentServiceImpl时,就可以把StudentRepository接口Mock掉,这个被Mock的StudentRepository接口实例就拥有StudentRepository接口的所有方法,并且给这些方法以最基本的实现
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentRepository studentRepository;
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
//被测试类
@SpringBootTest(classes = StudentServiceImpl.class)
class StudentServiceImplTest {
@Autowired
private StudentServiceImpl studentService; // 注入被测试列
@MockBean
private StudentRepository studentRepository; // Mock被测试类的依赖
}