springboot项目添加websocket依赖后运行测试类报如下错误:
解决办法:为SpringbootTest注解指定参数classes和webEnvironment
- @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
- 因为WebSocket是servlet容器所支持的,所以需要加载servlet容器:
webEnvironment参数为springboot指定ApplicationContext类型。
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT表示内嵌的服务器将会在一个随机的端口启动。
- WebEnvironment主要有一下类型:
- 1 enum WebEnvironment {
- 2
- 3 /**
- 4 * Creates a {@link WebApplicationContext} with a mock servlet environment if
- 5 * servlet APIs are on the classpath, a {@link ReactiveWebApplicationContext} if
- 6 * Spring WebFlux is on the classpath or a regular {@link ApplicationContext}
- 7 * otherwise.
- 8 */
- 9 MOCK(false),
- 10
- 11 /**
- 12 * Creates a web application context (reactive or servlet based) and sets a
- 13 * {@code server.port=0} {@link Environment} property (which usually triggers
- 14 * listening on a random port). Often used in conjunction with a
- 15 * {@link LocalServerPort} injected field on the test.
- 16 */
- 17 RANDOM_PORT(true),
- 18
- 19 /**
- 20 * Creates a (reactive) web application context without defining any
- 21 * {@code server.port=0} {@link Environment} property.
- 22 */
- 23 DEFINED_PORT(true),
- 24
- 25 /**
- 26 * Creates an {@link ApplicationContext} and sets
- 27 * {@link SpringApplication#setWebApplicationType(WebApplicationType)} to
- 28 * {@link WebApplicationType#NONE}.
- 29 */
- 30 NONE(false);
- 31
- 32 private final boolean embedded;
- 33
- 34 WebEnvironment(boolean embedded) {
- 35 this.embedded = embedded;
- 36 }
- 37
- 38 /**
- 39 * Return if the environment uses an {@link ServletWebServerApplicationContext}.
- 40 * @return if an {@link ServletWebServerApplicationContext} is used.
- 41 */
- 42 public boolean isEmbedded() {
- 43 return this.embedded;
- 44 }
- 45
- 46 }
对于springboot如何创建ApplicationContext,可以参考博客:https://blog.csdn.net/lilongjiu/article/details/78045062。