转载:https://blog.csdn.net/qq_30141957/article/details/81273829函数
项目中,有些函数须要处理某个服务的返回结果,而在对函数单元测试的时候,又不能启动那些服务,这里就能够利用Mockito工具。Mockito中的Mock和Spy均可用于拦截那些还没有实现或不指望被真实调用的对象和方法,并为其设置自定义行为。两者的区别在于:工具
一、Mock声明的对象,对函数的调用均执行mock(即虚假函数),不执行真正部分。单元测试
二、Spy声明的对象,对函数的调用均执行真正部分。测试
例:this
-
-
-
public void fun(String s) {
-
System.
out.println(s + " : fun");
-
-
-
-
-
public void fun1(String s) {
-
System.
out.println(s + " : fun1");
-
-
-
private void fun2(String s) {
-
System.
out.println(s + " : fun2");
-
-
-
-
-
-
Mock使用实例
一、使用doCallRealMethod().when()调用函数真正部分。spa
二、使用when().thenReturn自定义函数返回值。.net
-
import static org.mockito.ArgumentMatchers.anyString;
-
import static org.mockito.Mockito.doCallRealMethod;
-
import static org.mockito.Mockito.when;
-
-
-
-
-
import org.mockito.MockitoAnnotations;
-
-
-
-
-
-
-
-
-
MockitoAnnotations.initMocks(
this);
-
-
-
-
-
-
mockMain.
fun("mock test One");
-
-
-
-
-
-
doCallRealMethod().
when(mockMain).fun(anyString());
-
mockMain.
fun("mock test Two");
-
-
-
System.
out.println("val: " + mockMain.getVal());
-
-
-
when(mockMain.getVal()).thenReturn(10);
-
System.
out.println("val: " + mockMain.getVal());
-
-
-

Spy使用实例
一、使用when().thenReturn自定义函数返回值。3d
-
import static org.mockito.Mockito.when;
-
-
-
-
import org.mockito.MockitoAnnotations;
-
-
-
-
-
-
-
-
-
-
MockitoAnnotations.initMocks(
this);
-
-
-
-
-
-
spyMain.
fun("mock test One");
-
-
-
System.
out.println("val: " + spyMain.getVal());
-
-
when(spyMain.getVal()).thenReturn(10);
-
System.
out.println("val: " + spyMain.getVal());
-
-

参考文章:code
一、mockito中实现部分mock两种方式对象
二、@mock和@spy在mock私有方法的区别,使用@spy模拟私有方法进行测试时sonar统计是有覆盖率的
三、Mockito的参数匹配