Error creating bean with name ‘serverEndpointExporter’ 因为websocket导致spring boot项目单元测试启动失败解决
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'serverEndpointExporter' defined in class path resource [com/zf/config/WebSocketConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: javax.websocket.server.ServerContainer not available
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1794) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
在项目中引入了websocket功能主要作用于消息的推送,但是在进行其它方法Junit测试的时候发现出现如下错误
解决办法: @SpringBootTest()加入webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApplicationTests {
@Test
public void contextLoads() {
}
}
默认情况下,@SpringBootTest不会启动服务器。您可以使用的webEnvironment属性@SpringBootTest进一步完善测试的运行方式:
MOCK(默认):加载WebApplicationContext并提供模拟Web环境。使用此注释时,不会启动嵌入式服务器。如果您的类路径中没有网络环境,则此模式将透明地退回到创建常规非网络ApplicationContext。它可以与Web应用程序结合使用@AutoConfigureMockMvc或@AutoConfigureWebTestClient用于基于模拟的测试。
RANDOM_PORT:加载WebServerApplicationContext并提供真实的网络环境。嵌入式服务器将启动并在随机端口上侦听。
DEFINED_PORT:加载WebServerApplicationContext并提供真实的网络环境。嵌入式服务器将启动并在已定义的端口(来自application.properties)上或在的默认端口上进行侦听8080。
NONE:ApplicationContext通过使用加载,SpringApplication但不提供任何网络环境(模拟或其他方式)。