我有三种方法.当运行单元测试时,我需要下一个:
- 方法
serviceMethod_1
不调用REAL方法 - 方法
serviceMethod_2
调用REAL方法 - 方法
serviceMethod_1
调用REAL方法
这里定义了方法Mockito.spy()
Mockito.spy() - each method implementation are the real one, except if you have defined a mocked behaviour with when(..)
这正是我所需要的.
因此,下面是我的单元测试:
import org.mockito.Spy;
@Spy
private MyServiceImpl myServiceSpy;
@Before
public void setup() {
System.out.println("\nSETUP");
}
@Test
public void myService_method_1_spy() {
when(myServiceSpy.serviceMethod_1())
.thenReturn("call_serviceMethod_1_MOCK");
List<String> actualList = myServiceSpy.performService();
List<String> expectedList = Arrays.asList(
"call_serviceMethod_1_MOCK",
"call_serviceMethod_2_REAL",
"call_serviceMethod_3_REAL");
assertEquals(expectedList, actualList);
verify(myServiceSpy, times(1)).serviceMethod_1();
}
这里的服务级别:
public class MyServiceImpl implements MyService {
private String text;
@Override
public String serviceMethod_1() {
String result = "call_serviceMethod_1_REAL";
System.out.println("serviceMethod_1: result = " + result);
return result;
}
@Override
public String serviceMethod_2() {
String result = "call_serviceMethod_2_REAL";
System.out.println("serviceMethod_2: result = " + result);
return result;
}
@Override
public String serviceMethod_3() {
String result = "call_serviceMethod_3_REAL";
System.out.println("serviceMethod_3: result = " + result);
return result;
}
@Override
public List<String> performService() {
System.out.println("performService: START, this.className = " + this.getClass().getName()); // In the name contain word "MockitoMock"
List<String> list = new ArrayList<>();
String item_1 = serviceMethod_1();
String item_2 = serviceMethod_2();
String item_3 = serviceMethod_3();
list.add(item_1);
list.add(item_2);
list.add(item_3);
return list;
}
public void setText(String text) {
this.text = text;
}
}
但是,当我运行测试时,我会得到下一个输出:
SETUP
serviceMethod_1: result = call_serviceMethod_1_REAL
performService: START, this.className = com.myproejctjava.javatestproject.service.MyServiceImpl$MockitoMock$Il2iukBL
serviceMethod_2: result = call_serviceMethod_2_REAL
serviceMethod_3: result = call_serviceMethod_3_REAL
BUILD SUCCESSFUL in 1s
正如您在测试调用REAL方法serviceMethod_1
中看到的那样.
为什么方法spy()
对我没有帮助?我不需要调用REAL方法serviceMethod_1