【发布时间】: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