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

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

}

我也看到过同样的问题 here但没有任何帮助。我可以知道我错过了什么吗?

我在依赖层次结构中有 spring-boot-starter-tomcat 作为编译时依赖。

最佳答案

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

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

* 解决方案 *

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

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

或者还启用 AutoConfiguration 以对这些 bean 进行类路径扫描和自动配置。

@EnableAutoConfiguration
WebsocketSourceConfiguration

也可以在集成测试课上完成。

@EnableAutoConfiguration
WebSocketSourceIntegrationTests

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

关于java - Spring Boot Test 失败说,由于缺少 ServletWebServerFactory bean,无法启动 ServletWebServerApplicationContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48264118/

相关文章:

java - Spring boot @Scheduled 失败 SQL 错误 : 17008, SQLState: 08003

java - jackson :使用时区 ID 解析 ZonedDateTime

java - LibGDX 游戏暂停状态 : Animation flicker/bug

java - Thymeleaf + Spring 下拉菜单在选定的下拉框中保留数据

java - Opengl Quads 不渲染

spring - PSQLException - spring boot 1.4.1 - spring data jpa - offsetdatetime/localdatetime 标识为字节流

java - Spring MVC中如何集成多种 View 技术

java - 使用 Confluence Kafka Avro Serializer 进行 Spring Kafka 测试找不到 ZKClientConfig

java - 一个图标中有多个动画图像?

java - 针对 dcterms :subject returns no results 的葡萄牙语 dbpedia 端点的 SPARQL 查询