0

How can I write a unit test for an override method? the code looks like this, but I can't get more code covergae for the override method.

public MessageHandler handler() {
    return new MessageHandler() {
        @SneakyThrows
        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            log.info("Fetching " + message.getPayload());
            var file = (File) message.getPayload();

            var content = Files.readString(Path.of(file.getPath()));

            List<String> fields = Arrays.stream(content.split(";"))
                    .map(String::trim)
                    .collect(Collectors.toList());

            if(((File) message.getPayload()).getName().startsWith("ACH")) {
                log.info("Backup: ", file);
                sftpGetAway.sendToSftpUploaded(file);
            }else {
                log.info("Backup: ", file);
                sftpGetAway.sendToSftpNonUploaded(file);
            }

            processFile(((File) message.getPayload()).getName(), fields);
        }
    };
}

The unit test code is this.

  @Test
public void handler() throws BadRequestException, IOException {
    Message<?> message = MessageBuilder.withPayload("@inboundtest.start()")
            .setHeader("SOME_HEADER_KEY", "SOME_HEADER_VALUE")
            .build();

    MessageHandler hand = Mockito.spy(MessageHandler.class);

    doNothing().when(hand).handleMessage(any(Message.class));
    MessageHandler handler = processAchServiceImp.handler();
    hand.handleMessage(message);
    Assert.assertNotNull(handler);
}

The test runs good but the coverage can't increase.

1 Answers1

0

Seems like you are mocking the class undertest :

MessageHandler hand = Mockito.spy(MessageHandler.class);
doNothing().when(hand).handleMessage(any(Message.class));

You should mock your dependcies instead. This link should give more explaination about your issue.

Harry Coder
  • 2,429
  • 2
  • 28
  • 32