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();
}
}
}
注:文章来源地址https://www.toymoban.com/news/detail-757152.html
- message.json为消息体内容的json文件
- 重点关注@MockBean和Mockito的使用
- readData为从文件中读取json对象的方法
文章来源:https://www.toymoban.com/news/detail-757152.html
到了这里,关于基于spring mockito 编写kafka消费者的单元测试的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!