Search code examples
javaunit-testingjunitmockitojunit4

JUnit 4.xx (Java) Trouble with Mockito when Trying to Get Line Coverage


The following is my main code.

public class KafkaConsumerForTests {

private ConsumerRecords<String, String> records;
private GenericKafkaConsumer<String, String> consumer;

    @Override
    public void run() {

        try {

            while (true) {

               LOGGER.logp(Level.INFO, CLASS_NAME, "run()", "Attempting to Poll");
               records = consumer.poll(10000);
               int numOfRecords = records.count();

               **if (numOfRecords == 0) {** // I want to get line coverage for this branch

                LOGGER.logp(Level.INFO, CLASS_NAME, "run()", "No Response. Invalid Topic");
                break;
            }

            **else if(numOfRecords > 0) {** // I want to get line coverage for this branch.

                LOGGER.logp(Level.INFO, CLASS_NAME, "run()", "Response Received");
            }
        }

    } catch (WakeupException e) {
        consumer.close();
    }

  }

}

As you can see I want to get line coverage for the following branches to test if it's correctly logging. I tried mocking out instances of records.count(); You can see my code for the test case below.

@Test
public void testRunWithZeroRecords() throws IOException {

    KafkaConsumerForTests consumerThread3 = spy(new KafkaConsumerForTests("topic_pleasestuff", "lmao"));

    ConsumerRecords<String, String> mock2 = mock(ConsumerRecords.class);

    consumerThread3.records = mock2;

    when(mock2.count()).thenReturn(9);

    consumerThread3.run();

    //verify(mock2, times(1)).count();
}

No matter what I do, I'm not hitting:

else if(numOfRecords > 0)

I am returning a number greater than 0. It's as if records.count(); isn't even being executed in the mock. I apologize for any convention or StackOverflow question syntax errors. I'm new to the Java community.


Solution

  • Your mock2.count() isn't happening, because ahead of the call to count() in the method you're testing, you reassign records to the result of consumer.poll(10000);.

    You'll need to create mocks, say mockRecords and mockConsumer; and then inject consumer with the mock that you created. Then include a stub line like

    doReturn(mockRecords).when(mockConsumer).poll(10000);
    

    before your call to run.