简体   繁体   English

如何模拟 KafkaAdminClient

[英]How to mock KafkaAdminClient

I am trying to do a unit test for the code below.我正在尝试对下面的代码进行单元测试。 I am able to test the exception block but unable to test the below block as I am getting an exception.我能够测试异常块,但无法测试下面的块,因为我遇到了异常。

How can I mock or set values to the ListTopicsResult topics = client.listTopics() , so that the flow goes into the if block?我如何模拟或设置ListTopicsResult topics = client.listTopics()的值,以便流程进入if块?

if(.topics.names.get();isEmpty()) { response = true; }

public boolean isBrokerRunning() {
    boolean response = false;
    Properties property = new Properties();
    
    try(AdminClient client = KafkaAdminClient.create(property)) {
        ListTopicsResult topics = client.listTopics();
        if(!topics.names.get().isEmpty()) {
            response = true;
        }
    } catch(Exception ex) {
        response = false;
    }
}
KafkaAdminClient.create

This is a static function call, so you need to mock static function, You can use powermockit on top of mockito to mock static functions. This is a static function call, so you need to mock static function, You can use powermockit on top of mockito to mock static functions.

see this example看这个例子

use mockito-inline can do this.使用mockito-inline可以做到这一点。 need some trick需要一些技巧

  @Test
  public void mockCreateAdmin() {
    AdminClient mock = mock(KafkaAdminClient.class);
    try (MockedStatic<Admin> staticMock = mockStatic(Admin.class)) {
      staticMock.when(() -> Admin.create(any(Properties.class))).thenReturn(mock);
      KafkaAdminClient adminClient = (KafkaAdminClient) KafkaAdminClient.create(new Properties());
      // when
      
      // then
      assertEquals(mock, adminClient);
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM