编程语言
首页 > 编程语言> > java – Spring启动测试失败说,由于缺少ServletWebServerFactory bean,无法启动ServletWebServerApplicationContext

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

作者:互联网

测试类: –

@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****************************************************");
    }

}

我见过同样的问题here,但没有任何帮助我.我可以知道我错过了什么吗?

我在依赖关系层次结构中将spring-boot-starter-tomcat作为编译时依赖项.

解决方法:

这条消息说:
您需要在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();
  }
}

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

@EnableAutoConfiguration
WebsocketSourceConfiguration

也可以在Integration Test类中完成.

@EnableAutoConfiguration
WebSocketSourceIntegrationTests

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

标签:java,spring,spring-boot,spring-cloud-stream
来源: https://codeday.me/bug/20190928/1829378.html