Resolving ServerContainer Not Available Error in Spring Boot WebSocket Tests
When running test classes in a Spring Boot application with WebSocket integration, you may encounter the error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'serverEndpointExporter'
Invocation of init method failed; nested exception is java.lang.IllegalStateException:
javax.websocket.server.ServerContainer not available
This occurs because WebSocket funcsionality requires a servlet container, which isn't automatically initialized in test contexts by default. The solution is to explicitly configure the test environment:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WebSocketTest {
// Test methods
}
Key configuration options for webEnvironment:
RANDOM_PORT: Starts an embedded server on a random portDEFINED_PORT: Uses a defined port (from application.properties)MOCK: Creates a mock servlet environmentNONE: Doesn't start any web environment
For WebSocket testing, either RANDOM_PORT or DEFINED_PORT must be used to ensure the servlet container is available. The random port approach is generally preferred to avoid port conflicts during testing.