Mockito正在调用真实方法而不是存根

evrscar2  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(187)

我已经模拟了几个依赖项并定义了它们的行为。我不希望在我的依赖项上调用真正的方法--这就是模拟的全部意义。
我的测试:

@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());
}

特别是,realtransformationService.transformMultiDocData()方法在不应该被调用的时候被调用。
运行测试时的错误:

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

有人知道这里发生了什么吗?

ymdaylpp

ymdaylpp1#

您应该这样编写测试:

@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());
    }
}

相关问题