如何使用mockito测试kafka生产者的send方法和回调?

zdwk9cvp  于 2021-06-04  发布在  Kafka
关注(0)|答案(0)|浏览(387)

我试图测试一种方法,为此我使用mockito。然而,我的mock并没有进入if的状态,而是直接进入flush的行。
我想测试以下情况:

public class SomeClass{
     @Autowired
     private Producer<String, SpecificRecord> producer;

     private static final Logger LOGGER = Logger.Factory.getLogger(SomeClass.class);

     public void sendMessage(String topic, SpecificRecord message, Map<String,String> headers){
         ProducerRecord<String, SpecificRecord> avroMessage = new ProducerRecord<>(topic, null, null, "key",message, headers);
         producer.send(avroMessage, (metadata, exception) -> {
             if(exception == null ) {
                 LOGGER.info("OK");
             }else{ 
                 LOGGER.info("NOK");
             }
         });
         producer.flush();
    }

我要做的是:

@RunWith(MockitoJUnitRunner.class)
public class SomeClassTest{
    @InjectMocks
    private SomeClass someclass;

    @Mock
    private Producer<String,SpecificRecord> producer;

    @Mock
    private SpecificRecord message;

    @Mock
    private Logger logger;

    @Test
    public void sendMessageTest(){
        when(producer.send(any(ProducerRecord.class),any(Callback.class))).thenReturn(null);
        doNothing().when(producer).flush();

        someclass.sendMessage("topic", message, new HashMap<String,String>());
        verify(logger).info("OK");
    }
}

我该怎么做才能正确地模拟这种情况?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题