java - 如何在 Spring 集成测试中启动应用程序?
问题描述
我需要为我的应用程序创建一个集成测试。我使用@SpringBootTest(classes = {Application.class})
注释来启动它,但它的启动需要时间。那么,当我的应用程序准备就绪时,我该如何运行测试呢?
问题出在kafka监听器中:
@SpringBootApplication
public class Application {
@Autowired
private KafkaConsumeHandler kafkaConsumeHandler;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@KafkaListener(topics = "${kafka.topics.test}", containerFactory = "kafkaListenerContainerFactory")
public void listenRegistred(KafkaMessage consumeKafka) {
kafkaConsumeHandler.handleStartProcess(consumeKafka);
}
如果我尝试在测试中立即发送消息,侦听器将无法捕获它们。所以我在发送前稍作停顿。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
@DirtiesContext
public class ProcessTest {
@ClassRule
public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, "testTopic");
@Test
public void sendTestRegistred() throws Exception {
Thread.sleep(5000); // Need a delay to boot an application
...
}
解决方案
您需要添加带有注释的类@SpringBootApplication
。
例子:
@SpringBootApplication
public class SpringApp {}
@SpringBootTest(classes = SpringApp.class)
public class IntegrationTest {}
另外,请注意,集成测试总是比单元测试慢,您需要确定测试某个功能所需的测试类型。
有问题的更新后更新:
在您的情况下,测试的延迟是由于等待KafkaEmbded
开始而引起的。因此,您必须找到一种以编程方式确定何时Kafka
准备就绪的方法。这是应该起作用的一种可能性:
@Before
public void setUp() throws Exception {
// wait until the partitions are assigned
for (MessageListenerContainer messageListenerContainer :
kafkaListenerEndpointRegistry.getListenerContainers()) {
ContainerTestUtils.waitForAssignment(messageListenerContainer,
embeddedKafka.getPartitionsPerTopic());
}
代码取自这里:https ://github.com/code-not-found/spring-kafka/blob/master/spring-kafka-avro/src/test/java/com/codenotfound/kafka/SpringKafkaApplicationTest.java# L42
如果这不起作用,请查看如何等待KafkaEmbedded
启动。您的问题不是由 SpringBootTest 引起的。
推荐阅读
- kotlin - Mapstruct Kotlin Gradle - 接口实现不完整
- c# - 实体框架 - 如果新添加到集合中则插入,如果从集合中删除则删除
- spring - @Cacheable 抽象的 Spring Data Geode Expiration
- python - 面临的问题:UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 918: ordinal not in range(128) while trying to load a Pytorch model
- python-3.x - 我的代码的哪一部分打印了这个特定的行?
- typescript - 在 Slide ionic 5 上播放视频
- if-statement - 我在 verilog 中的 if 和 else 语句没有给出预期的结果
- android - 导航组件 - 在导航图中访问 BuildConfig
- ios - 未找到模块“firebase_core”颤振示例动态链接测试项目
- c - _findnext() 在有很多文件时返回一个大小为 1 的列表