我喜欢对一些春天的kafka听众进行单元测试。这在生产中很好用,但我在单元测试中遇到了一些问题。我使用spring配置bean重新定义了配置,但从不调用监听器。我错过了什么吗?
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {KafkaSpringBootTest.class})
@Configuration
@DirtiesContext
public class KafkaSpringBootTest {
@ClassRule
public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1);
@BeforeClass
public static void setup() {
System.setProperty("spring.kafka.bootstrap-servers", embeddedKafka.getBrokersAsString());
System.setProperty("spring.cloud.stream.kafka.binder.zkNodes", embeddedKafka.getZookeeperConnectionString());
System.setProperty("spring.kafka.consumer.auto-offset-reset", "earliest");
}
@Bean
public Map<String, Object> producerConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, embeddedKafka.getBrokersAsString());
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
return props;
}
@Bean
public ProducerFactory<String, String> producerFactory() {
return new DefaultKafkaProducerFactory<>(producerConfigs());
}
@Bean
public DefaultKafkaConsumerFactory<String, String> consumerFactory() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, embeddedKafka.getBrokersAsString());
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
return new DefaultKafkaConsumerFactory<>(props);
}
@Bean
public KafkaTemplate<String, String> kafkaTemplate() {
return new KafkaTemplate<>(producerFactory());
}
@Bean
public KafkaTransferListener kafkaTransferListener() {
return new KafkaTransferListener();
}
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Test
public void testSendMessage() throws InterruptedException {
System.out.println("now sending");
kafkaTemplate.send("test", "hello");
Thread.sleep(5000);
}
}
class KafkaTransferListener {
@KafkaListener(topics = "test")
public void listen(String test) {
System.out.println("received message via kafka: " + test);
}
}
版本:
提前致谢
答案 0 :(得分:1)
我没有看到@SpringBootApplication
配置以确保Spring Kafka是自动配置的。
您使用KafkaEmbedded
及其属性来配置ProducerConfig
,但同时我看不到您如何配置ConsumerConfig
。基本上,您应该使用EmbeddedKafka
。
使用Boot自动配置,你真的不需要所有那些功夫。有一种最简单的方法可以针对EmbeddedKafka
配置所有内容:
@BeforeClass
public static void setup() {
System.setProperty("spring.kafka.bootstrap-servers", embeddedKafka.getBrokersAsString());
System.setProperty("spring.cloud.stream.kafka.binder.zkNodes", embeddedKafka.getZookeeperConnectionString());
}
你肯定必须在与此测试相同的包中拥有@SpringBootApplication
类。其余的一切都将由Boot完成。
有关此事,请参阅this sample。