我在与WebSockets和SpringBoot进行集成测试时遇到问题。 如果我尝试从网页连接StomJS,则客户端会收到通知。 但是在与Java客户端的集成测试中,我遇到了异常。编写这些测试的正确方法是什么? 我的Config类如下:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends
AbstractWebSocketMessageBrokerConfigurer {
@Autowired
private ConnectionInterceptor connectionInterceptor;
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(connectionInterceptor);
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry
.addEndpoint(ApiConstants.SOCKET_BASE_URL)
.setAllowedOrigins("*")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker( "/topic", "/queue" );
registry.setApplicationDestinationPrefixes("/app");
registry.setUserDestinationPrefix("/user");
}
}
我的测试是:
@Test
@WithMockUser(authorities = "ADMIN")
public void ShouldLogoutGroupOfUsers() throws Exception {
String url = "ws://127.0.0.1:" + port+ "/socket";
StompSessionHandler sessionHandler = new MyStompSessionHandler();
CompletableFuture<SocketMessage> completable = new
CompletableFuture<>();
val stompHeaders = new StompHeaders();
//add authorization headers
stompHeaders.add(
tokenHeaderKey,
getUserHeaders().getValuesAsList(tokenHeaderKey).get(0)
);
val session = getStompClient().connect(
url,
new WebSocketHttpHeaders(),
stompHeaders,
new StompSessionHandlerAdapter() {
}
).get(1, SECONDS);
assertTrue(session.isConnected());
stompHeaders.setDestination("/user/queue/action/logout");
val subscription = session.subscribe(
stompHeaders,
new StompMessageHandler<>(completable,
SocketMessage.class)
);
现在我调用将要调用的控制器方法:
sender.convertAndSendToUser(registeredUser, DEVICE_LOGOUT_PATH,new
SocketMessage("hello socket"));
在这一行上测试失败:
SocketMessage message = completable.get(30, SECONDS);