转载自:https://blog.csdn.net/fggdgh/article/details/87185555
springboot项目添加websocket依赖后运行测试类报如下错误:
解决办法:为SpringbootTest注解指定参数classes和webEnvironment
@SpringBootTest(classes = WebsocketServerTestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
因为WebSocket是servlet容器所支持的,所以需要加载servlet容器:
webEnvironment参数为springboot指定ApplicationContext类型。
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT表示内嵌的服务器将会在一个随机的端口启动。
webEnvironment 主要的值可以参考SpringbootTest源码:
/** * An enumeration web environment modes. */ enum WebEnvironment { /** * Creates a {@link WebApplicationContext} with a mock servlet environment if * servlet APIs are on the classpath, a {@link ReactiveWebApplicationContext} if * Spring WebFlux is on the classpath or a regular {@link ApplicationContext} * otherwise. */ MOCK(false), /** * Creates a web application context (reactive or servlet based) and sets a * {@code server.port=0} {@link Environment} property (which usually triggers * listening on a random port). Often used in conjunction with a * {@link LocalServerPort} injected field on the test. */ RANDOM_PORT(true), /** * Creates a (reactive) web application context without defining any * {@code server.port=0} {@link Environment} property. */ DEFINED_PORT(true), /** * Creates an {@link ApplicationContext} and sets * {@link SpringApplication#setWebApplicationType(WebApplicationType)} to * {@link WebApplicationType#NONE}. */ NONE(false); private final boolean embedded; WebEnvironment(boolean embedded) { this.embedded = embedded; } /** * Return if the environment uses an {@link ServletWebServerApplicationContext}. * @return if an {@link ServletWebServerApplicationContext} is used. */ public boolean isEmbedded() { return this.embedded; } }