尝试获取行覆盖范围时,Mockito的JUnit 4.xx(Java)故障

以下是我的主要代码。


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

    }


  }


}

如您所见,我想获取以下分支的行覆盖范围,以测试其是否正确记录了日志。我试图模拟出records.count();的实例;您可以在下面查看我的测试用例代码。


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

}

无论我做什么,我都不会打:


否则if(numOfRecords> 0)


我返回的数字大于0。就好像records.count();一样。甚至没有在模拟中执行。对于任何约定或StackOverflow问题语法错误,我深表歉意。我是Java社区的新手。


缥缈止盈
浏览 197回答 1
1回答

饮歌长啸

您mock2.count()没有发生任何事情,因为count()在您要测试的方法中调用之前,您将重新分配records给的结果consumer.poll(10000);。您需要创建模拟,说mockRecords和mockConsumer;然后注入consumer您创建的模拟。然后加入一个存根线doReturn(mockRecords).when(mockConsumer).poll(10000);在您致电之前run。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java