【问题标题】:Getting NullPointerException when trying to unit test kafka publisher controller尝试对 kafka 发布者控制器进行单元测试时获取 NullPointerException
【发布时间】:2021-08-29 09:57:30
【问题描述】:

我正在尝试测试在 Kafka 主题中发布的控制器,但我的单元测试不断下降,因为我的 kafkaTemplate.send() 为空。

控制器类

public class Controller {

  private final KafkaTemplate<String, Object> kafkaTemplate;
  private final PublisherServices publisherServices;
  private static final String TOPIC = "Kafka publisher";

  @PostMapping("/publish_to")
  public String postTo(@RequestBody final RequestModel limitMessage)
        throws ExecutionException, InterruptedException {
     if(limitMessage.getCount() <= 0){
        return "your count is less than 0, there's nothing to be published!";
     }

     for (int countToBePublished = limitMessage.getCount();
       countToBePublished > 0;
       countToBePublished--) {
         log.info("publishing count  {} ", countToBePublished);
         kafkaTemplate
            .send(TOPIC, publisherServices.message(limitMessage))
            .get();
     }

     return "Published successfully to topic";
}

Controller 类的单元测试

//unit test
def "published the topic"() {

  def kafkaTemplateMock  = Mock(KafkaTemplate.class)
  def publisherServicesMock = Mock(PublisherServices)
  def controller = new Controller(kafkaTemplateMock,publisherServicesMock)

  given:
  def model = new RequestModel(1234, "2345", "topic" )
  def TOPIC = "Kafka publisher"

  when:
  Controller.postTo(model)
  def response = kafkaTemplateMock.send(TOPIC, model)
  kafkaTemplateMock.send(TOPIC, model)
  then:
  1 * controller.postTo(model)
  response == "Published successfully to topic"
}


        

【问题讨论】:

    标签: spring-boot unit-testing groovy apache-kafka spock


    【解决方案1】:

    您的代码有几处问题。

    1. 您正试图为非模拟 1 * controller.postTo(model) 断言执行
    2. 您将kafkaTemplateMock 视为不是模拟的。
    3. Controller.postTo(model) 这是一个静态调用

    Mocks 默认返回 null,你需要 stub 返回值,或者如果你也断言执行你需要结合 mocking and stubbing

    从您的代码来看,它可能如下所示:

    def "published the topic"() {
      given:
      KafkaTemplate kafkaTemplateMock  = Mock()
      PublisherServices publisherServicesMock = Mock()
      def controller = new Controller(kafkaTemplateMock,publisherServicesMock)
    
      def model = new RequestModel(1234, "2345", "topic" )
      def TOPIC = "Kafka publisher"
    
      when:
      def response = controller.postTo(model)
    
      then:
      1 * kafkaTemplateMock.send(TOPIC, model) >> Optional.of("") // Here you need to return whatever the real method would return, as you haven't shared this part of the code, I assume Optional, as it has a get method, could also be a Future or anything else
      response == "Published successfully to topic"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-24
      • 2017-04-26
      相关资源
      最近更新 更多