Issue
I have a class RequestProcessor with a method:
public ResponseClass process(Request request) {
String requestId = requestService.saveRequest(request);
ResponseClass response = new Response();
response.setId(requestId);
return response;
}
I need to write a test using Mockito, I came up with:
public class RequestProcessor {
@InjectMocks
private RequestProcess sut;
@Mock
private RequestService requestService;
@Test
public void test() {
String requestId = UUID.randomUUID().toString();
Request request = new Request(); //then setting up values of request
Mockito.when(requestService.saveRequest(request).thenReturn(requestId);
ResponseClass response = sut.process(request);
Assert.assertEquals(response.getRequestId(), requestId)
}
But the response.getRequestId() return null. What is the problem?
Solution
This might be due to a missing mock behaviour of sut.process(request). Can you add the mock behaviour of sut.process(request) too?
public class RequestProcessor {
@InjectMocks
private RequestProcess sut;
@Mock
private RequestService requestService;
@Test
public void test() {
String requestId = UUID.randomUUID().toString();
Request request = new Request(); //then setting up values of request
Mockito.when(requestService.saveRequest(request).thenReturn(requestId);
Mockito.when(sut.process(request).thenCallRealMethod();
ResponseClass response = sut.process(request);
Assert.assertEquals(response.getRequestId(), requestId)
}
Answered By - Annamalai Palanikumar
Answer Checked By - Mary Flores (JavaFixing Volunteer)