[英]Initialize application context during testing excluding the spring integration beans
我正在開發使用 Spring 集成和 Mqtt 支持的 Spring 引導應用程序。 這里我們有一個測試來檢查應用程序上下文是否正確啟動。
class ApplicationTests {
private @Autowired transient ApplicationContext applicationContext;
@Test
void mainMethodTest() {
Application.main(new String[] {});
Assertions.assertNotNull(this.applicationContext);
}
}
但如果 Mqtt 代理未運行,則此測試將執行。
@Bean
@ConfigurationProperties(prefix = "mqtt")
public MqttConnectionOptions mqttConnectOptions() {
return new MqttConnectionOptions();
}
@Bean
@DependsOn("mqttConnectOptions")
public MessageHandler mqttOutbound() {
Mqttv5PahoMessageHandler mqttv5PahoMessageHandler =
new Mqttv5PahoMessageHandler(mqttConnectOptions(), QueueConfigs.CLIENT_ID);
mqttv5PahoMessageHandler.setAsync(true);
return mqttv5PahoMessageHandler;
}
@Bean
public IntegrationFlow simulatorReadingsOutFlow() {
return flow -> flow.handle(mqttOutbound());
}
測試將失敗,因為在測試期間如果沒有在環境中運行的mqtt 代理將不會創建上述bean 。 有沒有辦法在ApplicationContext的測試期間跳過與集成流相關的 bean 或模擬它們。
@ferrouskid 在評論中所說的解決方案之一是在您的@SpringBootTest
@MockBean
@MockBean
IntegrationFlow simulatorReadingsOutFlow;
另一種解決方案是在 class 方法上使用@SpringIntegrationTest(noAutoStartup = "mqttOutboundEndpoint")
。 But it is going to work only if really use Spring Testing Framework, including or not Spring Boot: https://docs.spring.io/spring-integration/docs/current/reference/html/testing.html#test-context .
但是,如果您自己這樣做Application.main(new String[] {});
,您不依賴 Spring 測試環境,您只需在測試 scope 之外運行整個應用程序。 考慮了解更多如何測試 Spring 啟動項目: https://docs.spring.io/spring-boot/#docs/current/reference/html/features.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.