Mockito Mock是什么
Mockito 可以mock 一个接口或类,创建一个类或接口的mock实例是指这个mock实例拥有这个类或接口的所有方法,并且给这些方法以最基本的实现
- 如果方法返回值是void,mock什么都不做
- 如果方法返回值是void,mock默认返回null或0等基本类型的值
使用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<String> list = mock(List.class);
list.add("xx");
verify(list, times(1)).add("xx");
verify(list, times(0)).add("y");
}
}
使用@MockBean注解创建一个类或接口的mock实例
在SpringBoot Test中,@MockBean注解可以创建接口的mock实例,添加mock对象到 Spring ApplicationContext中。例如StudentServiceImpl类需要依赖StudentRepository接口,那么在测试StudentServiceImpl时,就可以把StudentRepository接口Mock掉,这个被Mock的StudentRepository接口实例就拥有StudentRepository接口的所有方法,并且给这些方法以最基本的实现
- 如果方法返回值是void,mock什么都不做
- 如果方法返回值是void,mock默认返回null或0等基本类型的值
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentRepository studentRepository;
}
在它的测试类中,可以使用Mockito的mockbean功能
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被测试类的依赖
}
最后
以上就是纯情鼠标最近收集整理的关于Mockito mock的全部内容,更多相关Mockito内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复