小编典典

Spring Boot Test失败说,由于缺少ServletWebServerFactory bean而无法启动ServletWebServerApplicationContext

spring

测试类别:

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

}

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

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


阅读 1289

收藏
2020-04-21

共1个答案

小编典典

该消息表明: 你需要在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();
  }
}

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

@EnableAutoConfiguration
WebsocketSourceConfiguration

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

@EnableAutoConfiguration
WebSocketSourceIntegrationTests
2020-04-21