单元测试StompEndpoint时触发NullPointerException问题求助
问题解决:WebSocket配置测试的NullPointerException
问题根源:用Mockito创建的
StompEndpointRegistrymock对象,默认所有方法调用返回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
相关产品推荐
相关产品推荐

