Home > database >  Mockito is calling real method instead of stubs
Mockito is calling real method instead of stubs

Time:08-24

I have mocked several dependencies and defined their behavior. I do not wish for real methods to be called on my dependencies - the whole point of mocking.

My test:

@Test
public void should_Create_MultiDoc_Ticket() throws URISyntaxException{
    DataTransformationService transformationService = Mockito.mock(DataTransformationService.class);
    
    JSONObject samplePolicyData = createSamplePolicyData("Sample Multidoc Template");
    
    InteractiveRequest sampleInteractiveRequest = createSampleInteractiveRequest();
    when(transformationService.transformMultiDocData(createSampleInteractiveData())).thenReturn(createSampleInteractiveData());

    String ticketId = interactiveTicketService.createTicket(samplePolicyData.toString());

    assertThat(ticketId).isEqualTo("sampleTicketId");
    verify(transformationService, times(1)).transformMultiDocData(createSampleInteractiveData());
}

Specifically, the real transformationService.transformMultiDocData() method is being called, when it shouldn't be.

The error when I run the test:

org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://us-data-transformation-sample/template": us-data-transformation-sample; nested exception is java.net.UnknownHostException: us-data-transformation-sample
    at com.lmig.us.services.DataTransformationService.transformMultiDocData(DataTransformationService.java:114)
    at com.lmig.us.services.InteractiveTicketService.createTicket(InteractiveTicketService.java:56)
    at com.lmig.us.services.InteractiveTicketServiceTest$createTicket.should_Create_MultiDoc_Ticket(InteractiveTicketServiceTest.java:311)
    ... 82 more

Does anyone know what's going on here?

CodePudding user response:

You should write the test like this:

@ExtendWith(MockitoExtension.class)
public class InteractiveTicketServiceTest {
    @Mock
    DataTransformationService transformationService;

    @InjectMocks
    InteractiveTicketService interactiveTicketService;

    @Test
    public void should_Create_MultiDoc_Ticket() throws URISyntaxException{
        JSONObject samplePolicyData = createSamplePolicyData("Sample Multidoc Template");   
        InteractiveRequest sampleInteractiveRequest = createSampleInteractiveRequest();
        when(transformationService
            .transformMultiDocData(createSampleInteractiveData()))
            .thenReturn(createSampleInteractiveData());
        String ticketId = interactiveTicketService.createTicket(samplePolicyData.toString());
        assertThat(ticketId).isEqualTo("sampleTicketId");
        verify(transformationService, times(1)).transformMultiDocData(createSampleInteractiveData());
    }
}
  • Related