Issue
I am new to JUnit and Mockito. Can someone please guide how to mock the below rest template? My current mocking shows an error: Unfinished Stubbing.
Service
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();
}
}
Solution
You need to add initMocks() or openMocks() for mock initialisation like that:
@BeforeEach(for Junit5 @Before for Junit4)
void setUp(){
initMocks(this);
}
And then you should declare your mocks behavior in the "when-then" section:
when(restTemplate.getRequestFactory()).thenReturn(mock(RequestFactory.class));
Use mockito
for stubbing chain of invocation your methods.
Full version example:
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...
}
}
Answered By - Dmitrii Bykov
Answer Checked By - Pedro (JavaFixing Volunteer)