【发布时间】:2021-12-29 16:26:58
【问题描述】:
如何将一个模拟的结果使用/注入到另一个模拟中?
我觉得我做错了
int 参数始终为空
我使用 spy 是因为我测试的方法是无效的。 我可以使用 mockito 吗?
@RunWith(MockitoJUnitRunner.class)
public class Test {
@Mock
Utils utils;
@Mock
Custom custom;
@Spy
@InjectMocks
MyService service;
@Test
public void test(){
Mockito.when(utils.get("p")).thenReturn(1); //use result of it in the next mock call
Mockito.when(custom.isValid(1)).thenReturn(true); //custom use 1 here
Mockito.doCallRealMethod().when(service).doIt("p");
service.doIt("p");
Mockito.verify(service,Mockito.times(1)).doIt("p");
}
}
@Service
public class MyService {
Utils utils;
Custom custom;
public MyService(Utils utils) {
this.utils = utils;
}
public void doIt(String value){
int param = utils.get(value);
if(custom.isValid(param)){
//do it
}
}
}
【问题讨论】:
-
您模拟了调用
Mockito.when(utils.get("p")).thenReturn(1);,但您的示例调用显示utils.get("param")- 您确定您在模拟正确的方法调用吗? -
如何在服务类中初始化Utils bean?它不适用于测试和引导
-
更新了示例。 @DmitriiBykov 通过构造函数
标签: java junit mockito spring-test