【问题标题】:Java Mockito - How can I test this method?Java Mockito - 我如何测试这个方法?
【发布时间】:2020-08-29 02:04:49
【问题描述】:

我有一个在不同对象和服务之间进行复杂交互的方法,我想使用 Mockito 框架对其进行测试。我将不胜感激。

@Autowired
private SolicitationService solicitationService;

@Autowired
private ClientRestService clientRestService;

public void sendToClient() {
    this.solicitationService.getAllCnpjWithoutIntegration().forEach(sol -> {
        try {
            ClientDto dto = toClientDto(sol.getDocument(), sol.getName());
            Boolean exist = this.clientRestService.findClient(dto);

            //Exists Client
            if (exist) {
                this.solicitationService.create(this.toSolicitation(sol.getDocument(),  dto.getName()));
            }
        } catch (Exception e) {
            log.error("ERROR: Impossible create client {}", sol.getDocument());
        }
    });
}

我的测试类:当我尝试执行时收到此错误消息:“org.mockito.exceptions.misusing.UnnecessaryStubbingException: 检测到不必要的存根。 干净且可维护的测试代码需要零个不必要的代码。”

@ExtendWith(MockitoExtension.class)
class IntegrationServiceImplTest {

    @Mock
    private IntegrationService integrationService;

    @Mock
    private SolicitationService solicitationService;

    @Mock
    private CatcherRestClient catcherRestClient;

    @BeforeEach
    void setUp() {
    }

    @Test
    void contextLoads() {
        assertThat(integrationService).isNotNull();
        assertThat(solicitationService).isNotNull();
        assertThat(catcherRestClient).isNotNull();
    }

    @Test
    void doesSendToClient() {
        SolicitationEntity solicitationEntity = mock(SolicitationEntity.class);
        CellDto cellDto = mock(CellDto.class);
        JsonNode jsonNode = mock(JsonNode.class);

        when(solicitationService.getAllCnpjWithoutIntegration()).thenReturn(Arrays.asList(cellDto));
        when(catcherRestClient.produceCnpj(any())).thenReturn(jsonNode);
        when(solicitationService.create(any())).thenAnswer((invocation) -> {
                    SolicitationEntity entity = invocation.getArgument(0, SolicitationEntity.class);
                    return entity;
                }
        );

        assertDoesNotThrow(() -> integrationService.sendToClient());
    }

}

【问题讨论】:

  • 首先为这个方法应该做的功能编写测试,然后实现——你会看到这段代码的所有错误,从void开始。
  • 我在这里写了我的测试方法问题是当我执行覆盖率为0%
  • 您能否在测试中添加您在 bean/mock 中的接线方式?
  • @shinjw 我添加了完整的测试课程,但我不知道有什么问题。

标签: java unit-testing junit mockito


【解决方案1】:

由于您需要单元测试给定的类,因此仅模拟其依赖项,例如 solicitationService 而不是 solicitationRepository。

当模拟被模拟对象方法的行为时,你可以使用 thenReturn 或 thenAnswer 方法。在 thenAnswer 中,您可以获取传递给方法的 arg 值并断言这些值

@Test
void doesSendToClient() {
    when(solicitationRepository.getAllCnpjWithoutIntegration()).thenReturn(Arrays.asList(solicitationEntity));
    when(clientRestService.findClient(any())).thenReturn(true);
    when(solicitationService.create(any())).thenAnswer((invocation) -> {
        SolicitationDto solicitationDto =  invocation.getArgument(0, SolicitationDto.class);
                //assert data in dto and return require response
                return solicitationEntity;
            }
    );

    assertDoesNotThrow(() -> integrationService.sendToClient());
}

【讨论】:

  • @NikisVij 我尝试使用您的示例,但是我总是收到错误,并且对于解决方案,我需要删除“何时”,但如果我这样做了,我的覆盖率为 0%
  • 你改变了你的测试类。现在你甚至没有调用sendToClient 方法。你将如何测试这种行为?也更新你的服务类,如果你想测试 sendToClient 然后在你的测试中调用方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-06
  • 2011-04-12
  • 1970-01-01
  • 2018-11-14
  • 1970-01-01
相关资源
最近更新 更多