测试无法开始使用 spring-kafka-test (NoClassDefFoundError)

Tests fail to start using spring-kafka-test (NoClassDefFoundError)

我正在 spring-kafka-test 的帮助下测试使用 Kafka 生产者和侦听器的功能。

spring-kafkaspring-kafka-test 都在使用 2.8.2 版本。

我的测试类使用@EmbeddedKafka注解如下:

@SpringBootTest
@DirtiesContext
@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9092", "port=9092" })
class EmbeddedKafkaIntegrationTest {
    // Test cases
}

我在 运行 测试时得到以下堆栈跟踪:

Failed to resolve parameter [com.my-company.my-app.kafka.KafkaProducer kafkaProducer] in constructor [public com.my-company.my-app.kafka.DigitalKafkaListenerIT(com.my-company.my-app.kafka.KafkaProducer,com.my-company.my-app.config.ApplicationProperties)]: Failed to load ApplicationContext
org.junit.jupiter.api.extension.ParameterResolutionException: Failed to resolve parameter [com.my-company.my-app.kafka.KafkaProducer kafkaProducer] in constructor [public com.my-company.my-app.kafka.DigitalKafkaListenerIT(com.my-company.my-app.kafka.KafkaProducer,com.my-company.my-app.config.ApplicationProperties)]: Failed to load ApplicationContext
    at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameter(ExecutableInvoker.java:239)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    ... 77 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embeddedKafka': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: com/codahale/metrics/Reservoir
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804)
    ... 81 more
Caused by: java.lang.NoClassDefFoundError: com/codahale/metrics/Reservoir
    at org.apache.zookeeper.metrics.impl.DefaultMetricsProvider$DefaultMetricsContext.lambda$getSummary(DefaultMetricsProvider.java:126)
    ... 90 more
Caused by: java.lang.ClassNotFoundException: com.codahale.metrics.Reservoir
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 105 more

这可能是 spring-kafka-test2.8.2 version 中的错误。

切换回最新的次要 2.7.10 version 解决了问题,即使 spring-kafka 仍在 2.8.2 上。