我是 JUnit 和 Mockito 的新手。有人可以指导如何模拟下面的休息模板吗?我当前的模拟显示错误:未完成的存根。
服务
class MyService {
void func(){
(SimpleClientHttpRequestFactory).restTemplate.getRequestFactory()).setConnectTimeout(t1);
}
}
Mockito
Class MyTest {
@Inject
MyService service;
@Mock
RestTemplate template;
@Test
void testit(){
doNothing().when((SimpleClientHttpRequestFactory)
.restTemplate.getRequestFactory())).setTimeout(anyInt();
}
}
答案 0 :(得分:0)
您需要添加 initMocks() 或 openMocks() 以进行模拟初始化:
@BeforeEach(for Junit5 @Before for Junit4)
void setUp(){
initMocks(this);
}
然后你应该在“when-then”部分声明你的模拟行为:
when(restTemplate.getRequestFactory()).thenReturn(mock(RequestFactory.class));
使用 mockito
对方法调用链进行存根。
完整版示例:
Class MyTest {
@Inject
MyService service;
@Mock
RestTemplate template;
@BeforeEach
void setUp(){
initMocks(this);
}
@Test
void testit(){
RestTemplate template = mock(RestTemplate.class);
ClientHttpRequestFactory factory = mock(ClientHttpRequestFactory.class);
when(restTemplate.getRequestFactory()).thenReturn(template));
when(template.getRequestFactory).thenReturn(factory);
etc...
}
}