0


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

  1. import com.alibaba.fastjson.JSON;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.avris.strategy.worker.api.Application;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import javax.annotation.Resource;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.apache.kafka.clients.consumer.ConsumerRecord;
  9. import org.junit.Test;
  10. import org.junit.runner.RunWith;
  11. import org.mockito.Mockito;
  12. import org.springframework.boot.test.context.SpringBootTest;
  13. import org.springframework.boot.test.mock.mockito.MockBean;
  14. import org.springframework.kafka.support.Acknowledgment;
  15. import org.springframework.test.context.junit4.SpringRunner;
  16. @RunWith(SpringRunner.class)
  17. @SpringBootTest(classes = Application.class)
  18. @Slf4j
  19. public class KafkaComsumerTest {
  20. @Resource
  21. private KafkaComsumer kafkaComsumer;
  22. @MockBean
  23. private Acknowledgment acknowledgment;
  24. @MockBean
  25. private ConsumerRecord consumerRecord;
  26. @Test
  27. public void testKafkaComsumer() {
  28. String message = null;
  29. try {
  30. message = readData("message.json");
  31. } catch (IOException e) {
  32. log.error("读取文件失败", e);
  33. }
  34. Mockito.when(consumerRecord.value()).thenReturn(message);
  35. kafkaComsumer.comsumerMethod(consumerRecord, acknowledgment);
  36. }
  37. private String readData(String fileName) throws IOException {
  38. String path = "/testData/" + fileName;
  39. InputStream config = getClass().getResourceAsStream(path);
  40. if (config == null) {
  41. throw new RuntimeException("读取文件失败");
  42. } else {
  43. JSONObject json = JSON.parseObject(config, JSONObject.class);
  44. return json.toJSONString();
  45. }
  46. }
  47. }

注:

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

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

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

还没有评论