以下是我的主要代码。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();的实例;您可以在下面查看我的测试用例代码。@Testpublic 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社区的新手。
1 回答
饮歌长啸
TA贡献1951条经验 获得超3个赞
您mock2.count()
没有发生任何事情,因为count()
在您要测试的方法中调用之前,您将重新分配records
给的结果consumer.poll(10000);
。
您需要创建模拟,说mockRecords
和mockConsumer
;然后注入consumer
您创建的模拟。然后加入一个存根线
doReturn(mockRecords).when(mockConsumer).poll(10000);
在您致电之前run
。
添加回答
举报
0/150
提交
取消