且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring boot 测试失败说,由于缺少 ServletWebServerFactory bean,无法启动 ServletWebServerApplicationContext

更新时间:2021-09-22 16:51:59

此消息说:您需要在 ApplicationContext 中配置至少 1 个 ServletWebServerFactory bean,所以如果您已经有 spring-boot-starter-tomcat y您需要自动配置该 bean 或手动进行强>.

This message says: You need to configure at least 1 ServletWebServerFactory bean in the ApplicationContext, so if you already have spring-boot-starter-tomcat you need to either autoconfigure that bean or to do it manually.

所以,在测试中只有 2 个配置类来加载 applicationContext,它们是 = { WebsocketSourceConfiguration.class, WebSocketSourceIntegrationTests.class },那么至少在这些类中的一个类中应该有一个 @Bean 方法返回一个实例所需的 ServletWebServerFactory.

So, in the test there are only 2 configuration classes to load the applicationContext, these are = { WebsocketSourceConfiguration.class, WebSocketSourceIntegrationTests.class }, then at least in one of these classes there should be a @Bean method returning an instance of the desired ServletWebServerFactory.

* 解决方案 *

确保加载配置类中的所有bean

Make sure to load all the beans within your configuration class

WebsocketSourceConfiguration {
  @Bean 
  ServletWebServerFactory servletWebServerFactory(){
  return new TomcatServletWebServerFactory();
  }
}

OR 还启用 AutoConfiguration 对这些 bean 进行类路径扫描和自动配置.

OR also enable the AutoConfiguration to do a classpath scanning and auto-configuration of those beans.

@EnableAutoConfiguration
WebsocketSourceConfiguration

也可以在集成测试课程中完成.

Can be done also at the Integration Test class.

@EnableAutoConfiguration
WebSocketSourceIntegrationTests

有关更多信息,请查看 SpringBootTest 注释文档https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/context/SpringBootTest.html

For more information check the SpringBootTest annotation documentation https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/context/SpringBootTest.html