0


基于spring mockito 编写kafka消费者的单元测试

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.avris.strategy.worker.api.Application;
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Slf4j
public class KafkaComsumerTest {

  @Resource
  private KafkaComsumer kafkaComsumer;

  @MockBean
  private Acknowledgment acknowledgment;

  @MockBean
  private ConsumerRecord consumerRecord;

  @Test
  public void testKafkaComsumer() {
    String message = null;
    try {
      message = readData("message.json");
    } catch (IOException e) {
      log.error("读取文件失败", e);
    }

    Mockito.when(consumerRecord.value()).thenReturn(message);
    kafkaComsumer.comsumerMethod(consumerRecord, acknowledgment);
  }

  private String readData(String fileName) throws IOException {
    String path = "/testData/" + fileName;
    InputStream config = getClass().getResourceAsStream(path);
    if (config == null) {
      throw new RuntimeException("读取文件失败");
    } else {
      JSONObject json = JSON.parseObject(config, JSONObject.class);
      return json.toJSONString();
    }
  }

}

注:

  1. message.json为消息体内容的json文件
  2. 重点关注@MockBean和Mockito的使用
  3. readData为从文件中读取json对象的方法

本文转载自: https://blog.csdn.net/qq_35473192/article/details/131376171
版权归原作者 <Michael> 所有, 如有侵权,请联系我们删除。

“基于spring mockito 编写kafka消费者的单元测试”的评论:

还没有评论