You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单元测试StompEndpoint时触发NullPointerException问题求助

问题解决:WebSocket配置测试的NullPointerException
  • 问题根源:用Mockito创建的StompEndpointRegistry mock对象,默认所有方法调用返回null。在verify环节链式调用addEndpoint("/ws").withSockJS()时,addEndpoint返回null,后续调用withSockJS()触发空指针异常。

  • 修复代码:需要为addEndpoint方法指定返回的mock对象,让链式调用能正常执行。修改后的测试代码如下:

@Test
public void testRegisterStompEndpoints() {
    // Arrange
    StompEndpointRegistry registry = mock(StompEndpointRegistry.class);
    StompWebSocketEndpointRegistration registration = mock(StompWebSocketEndpointRegistration.class);
    
    // 配置mock:调用addEndpoint("/ws")时返回registration对象
    when(registry.addEndpoint("/ws")).thenReturn(registration);
    // 可选:配置withSockJS()返回自身,避免后续链式调用可能的问题
    when(registration.withSockJS()).thenReturn(registration);
    
    WebSocketConfig webSocketConfig = new WebSocketConfig();

    // Act
    webSocketConfig.registerStompEndpoints(registry);

    // Assert
    verify(registry, times(1)).addEndpoint("/ws");
    verify(registration, times(1)).withSockJS();
}
  • 黄色下划线说明:这是IDE静态检查的提示,原因是IDE检测到mock对象的方法调用未设置返回值,存在空指针风险。修复代码后该提示会自动消失。

内容的提问来源于stack exchange,提问作者mfy98

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 00:22:13