【发布时间】: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