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

Kri*_*has 19 java spring spring-boot spring-cloud-stream

测试类: -

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { WebsocketSourceConfiguration.class,
        WebSocketSourceIntegrationTests.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
                "websocket.path=/some_websocket_path", "websocket.allowedOrigins=*",
                "spring.cloud.stream.default-binder=kafka" })
public class WebSocketSourceIntegrationTests {

    private String port = "8080";

    @Test
    public void testWebSocketStreamSource() throws IOException, InterruptedException {
        StandardWebSocketClient webSocketClient = new StandardWebSocketClient();
        ClientWebSocketContainer clientWebSocketContainer = new ClientWebSocketContainer(webSocketClient,
                "ws://localhost:" + port + "/some_websocket_path");
        clientWebSocketContainer.start();
        WebSocketSession session = clientWebSocketContainer.getSession(null);
        session.sendMessage(new TextMessage("foo"));
        System.out.println("Done****************************************************");
    }

}
Run Code Online (Sandbox Code Playgroud)

在这里看到了同样的问题,但没有任何帮助.我可以知道我错过了什么吗?

spring-boot-starter-tomcat在依赖关系层次结构中具有编译时依赖性.

小智 23

此消息说: 您需要在ApplicationContext中配置至少1个ServletWebServerFactory bean,因此如果您已经有spring-boot-starter-tomcat,则需要自动配置该bean或手动执行此操作.

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

*解决方案*

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

WebsocketSourceConfiguration {
  @Bean 
  ServletWebServerFactory servletWebServerFactory(){
  return new TomcatServletWebServerFactory();
  }
}
Run Code Online (Sandbox Code Playgroud)

或者还使AutoConfiguration能够对这些bean进行类路径扫描和自动配置.

@EnableAutoConfiguration
WebsocketSourceConfiguration
Run Code Online (Sandbox Code Playgroud)

也可以在Integration Test类中完成.

@EnableAutoConfiguration
WebSocketSourceIntegrationTests
Run Code Online (Sandbox Code Playgroud)

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

  • 另外:`import org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration; @SpringBootTest(classes = {ServletWebServerFactoryAutoConfiguration.class,...})` (4认同)
  • 对我来说,当我的测试配置类中使用“@Configuration”而不是“@TestConfiguration”(在“@SpringBootTest”注释中的“类”下列出)时,就会发生这种情况 (2认同)