【已解决】项目中使用websocket的时候,使用Junit自测其他diam提示:webSocket初始化失败怎么办?

  • 作者: 凯哥Java(公众号:凯哥Java)
  • 经验分享
  • 时间:2024-03-05 10:31
  • 593人已阅读
简介 【已解决】项目中使用websocket的时候,使用Junit自测其他diam提示:webSocket初始化失败错误信息如下图:解决方案:

🔔🔔好消息!好消息!🔔🔔

 如果您需要注册ChatGPT,想要升级ChatGPT4。凯哥可以代注册ChatGPT账号代升级ChatGPT4

有需要的朋友👉:微信号 kaigejava2022

【已解决】项目中使用websocket的时候,使用Junit自测其他diam提示:webSocket初始化失败

错误信息如下图:5efca9da4de2552fc00b4072b5aa1243.png

现场复现:

我使用spring boot 和 junit测试。测试类如下:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {BaseBuildApplication.class})
public class ScoreProjectDictServerImplTest  {

    @Resource
    private IScoreProjectDictServer scoreProjectDictServer;


    @Test
    public void selectAllTest(){
        System.out.println("1:"+scoreProjectDictServer.getById(1));
    }
}

错误信息: Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'serverEndpointExporter' defined in class path resource [com/hdtd/safequality/business/login/config/WebSocketConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: javax.websocket.server.ServerContainer not available 怎么解决这个错误?


此错误信息表明Spring Boot在尝试创建serverEndpointExporter Bean时遇到了问题,原因是javax.websocket.server.ServerContainer不可用。这通常是因为在测试环境下,Spring Boot应用没有启动完整的Servlet容器,而WebSocket需要在Servlet容器中运行。

解决这个问题的一个方法是在测试环境下禁用WebSocket相关的配置。你可以通过以下几种方式之一来实现:

1. 使用条件注解

在你的WebSocketConfig配置类或者serverEndpointExporter Bean的定义上使用@ConditionalOnProperty@Profile注解,以确保仅在非测试环境下激活WebSocket配置。

示例使用@Profile:

@Configuration
@Profile("!test") // 只有在当前profile不是test时,这个配置类才会被激活
public class WebSocketConfig {
    // ...
}

示例使用@ConditionalOnProperty:

@Configuration
@ConditionalOnProperty(name = "websocket.enabled", havingValue = "true", matchIfMissing = true)
public class WebSocketConfig {
    // ...
}

然后在application.propertiesapplication.yml测试配置中设置websocket.enabled=false

2. 修改测试配置

在测试资源目录(src/test/resources)下创建或修改application.propertiesapplication.yml文件,加入相关配置以禁用WebSocket。

示例application.properties:

websocket.enabled=false

示例application.yml:

websocket:
  enabled: false


然后确保你的WebSocketConfig类或serverEndpointExporter Bean的创建基于这个属性。

3. 使用MockBean

如果你的测试确实需要ServerEndpointExporter Bean,但你不想启动完整的WebSocket服务器,你可以考虑在测试中使用@MockBean来模拟这个Bean。

fc864631b1f7f63d226d5c7431858450.png

示例:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {BaseBuildApplication.class})
public class ScoreProjectDictServerImplTest  {

    @MockBean
    private ServerEndpointExporter serverEndpointExporter;

    @Resource
    private IScoreProjectDictServer scoreProjectDictServer;

    @Test
    public void selectAllTest(){
        System.out.println("1:"+scoreProjectDictServer.getById(1));
    }
}

通过这种方式,你可以避免在测试环境中初始化WebSocket相关的组件。

说明:凯哥使用的就是第三中方案

选择最适合你的情况的方法来解决这个问题。通常,禁用或模拟测试环境下不需要的组件是解决这类问题的好方法。



TopTop