Migrate to Mockito.mock(T...) where feasible

This commit is contained in:
Sam Brannen
2023-01-19 14:32:29 +01:00
parent c3d123fef7
commit c4c786596f
369 changed files with 2267 additions and 2707 deletions

View File

@@ -17,11 +17,8 @@
package org.springframework.web.socket.adapter.jetty;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.UpgradeRequest;
import org.eclipse.jetty.websocket.api.UpgradeResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
@@ -31,46 +28,41 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Test fixture for {@link org.springframework.web.socket.adapter.jetty.JettyWebSocketHandlerAdapter}.
* Tests for {@link JettyWebSocketHandlerAdapter}.
*
* @author Rossen Stoyanchev
*/
public class JettyWebSocketHandlerAdapterTests {
class JettyWebSocketHandlerAdapterTests {
private JettyWebSocketHandlerAdapter adapter;
private Session session = mock();
private WebSocketHandler webSocketHandler;
private WebSocketHandler webSocketHandler = mock();
private JettyWebSocketSession webSocketSession;
private JettyWebSocketSession webSocketSession = new JettyWebSocketSession(null, null);
private Session session;
private JettyWebSocketHandlerAdapter adapter = new JettyWebSocketHandlerAdapter(this.webSocketHandler, this.webSocketSession);
@BeforeEach
public void setup() {
this.session = mock(Session.class);
given(this.session.getUpgradeRequest()).willReturn(Mockito.mock(UpgradeRequest.class));
given(this.session.getUpgradeResponse()).willReturn(Mockito.mock(UpgradeResponse.class));
this.webSocketHandler = mock(WebSocketHandler.class);
this.webSocketSession = new JettyWebSocketSession(null, null);
this.adapter = new JettyWebSocketHandlerAdapter(this.webSocketHandler, this.webSocketSession);
void setup() {
given(this.session.getUpgradeRequest()).willReturn(mock());
given(this.session.getUpgradeResponse()).willReturn(mock());
}
@Test
public void onOpen() throws Throwable {
void onOpen() throws Exception {
this.adapter.onWebSocketConnect(this.session);
verify(this.webSocketHandler).afterConnectionEstablished(this.webSocketSession);
}
@Test
public void onClose() throws Throwable {
void onClose() throws Exception {
this.adapter.onWebSocketClose(1000, "reason");
verify(this.webSocketHandler).afterConnectionClosed(this.webSocketSession, CloseStatus.NORMAL.withReason("reason"));
}
@Test
public void onError() throws Throwable {
void onError() throws Exception {
Exception exception = new Exception();
this.adapter.onWebSocketError(exception);
verify(this.webSocketHandler).handleTransportError(this.webSocketSession, exception);

View File

@@ -16,35 +16,40 @@
package org.springframework.web.socket.adapter.jetty;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.UpgradeRequest;
import org.eclipse.jetty.websocket.api.UpgradeResponse;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.core.testfixture.security.TestPrincipal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Unit tests for {@link org.springframework.web.socket.adapter.jetty.JettyWebSocketSession}.
* Unit tests for {@link JettyWebSocketSession}.
*
* @author Rossen Stoyanchev
*/
public class JettyWebSocketSessionTests {
class JettyWebSocketSessionTests {
private final Map<String, Object> attributes = new HashMap<>();
private final Map<String, Object> attributes = Map.of();
private final UpgradeRequest request = mock();
private final UpgradeResponse response = mock();
private final Session nativeSession = mock();
@Test
@SuppressWarnings("resource")
public void getPrincipalWithConstructorArg() {
void getPrincipalWithConstructorArg() {
TestPrincipal user = new TestPrincipal("joe");
JettyWebSocketSession session = new JettyWebSocketSession(attributes, user);
@@ -53,16 +58,13 @@ public class JettyWebSocketSessionTests {
@Test
@SuppressWarnings("resource")
public void getPrincipalFromNativeSession() {
void getPrincipalFromNativeSession() {
TestPrincipal user = new TestPrincipal("joe");
UpgradeRequest request = Mockito.mock(UpgradeRequest.class);
given(request.getUserPrincipal()).willReturn(user);
UpgradeResponse response = Mockito.mock(UpgradeResponse.class);
given(response.getAcceptedSubProtocol()).willReturn(null);
Session nativeSession = Mockito.mock(Session.class);
given(nativeSession.getUpgradeRequest()).willReturn(request);
given(nativeSession.getUpgradeResponse()).willReturn(response);
@@ -77,14 +79,11 @@ public class JettyWebSocketSessionTests {
@Test
@SuppressWarnings("resource")
public void getPrincipalNotAvailable() {
UpgradeRequest request = Mockito.mock(UpgradeRequest.class);
void getPrincipalNotAvailable() {
given(request.getUserPrincipal()).willReturn(null);
UpgradeResponse response = Mockito.mock(UpgradeResponse.class);
given(response.getAcceptedSubProtocol()).willReturn(null);
Session nativeSession = Mockito.mock(Session.class);
given(nativeSession.getUpgradeRequest()).willReturn(request);
given(nativeSession.getUpgradeResponse()).willReturn(response);
@@ -99,16 +98,13 @@ public class JettyWebSocketSessionTests {
@Test
@SuppressWarnings("resource")
public void getAcceptedProtocol() {
void getAcceptedProtocol() {
String protocol = "foo";
UpgradeRequest request = Mockito.mock(UpgradeRequest.class);
given(request.getUserPrincipal()).willReturn(null);
UpgradeResponse response = Mockito.mock(UpgradeResponse.class);
given(response.getAcceptedSubProtocol()).willReturn(protocol);
Session nativeSession = Mockito.mock(Session.class);
given(nativeSession.getUpgradeRequest()).willReturn(request);
given(nativeSession.getUpgradeResponse()).willReturn(response);

View File

@@ -22,7 +22,6 @@ import jakarta.websocket.CloseReason;
import jakarta.websocket.CloseReason.CloseCodes;
import jakarta.websocket.MessageHandler;
import jakarta.websocket.Session;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.web.socket.CloseStatus;
@@ -36,31 +35,23 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Test fixture for {@link org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter}.
* Tests for {@link StandardWebSocketHandlerAdapter}.
*
* @author Rossen Stoyanchev
*/
public class StandardWebSocketHandlerAdapterTests {
class StandardWebSocketHandlerAdapterTests {
private StandardWebSocketHandlerAdapter adapter;
private WebSocketHandler webSocketHandler = mock();
private WebSocketHandler webSocketHandler;
private Session session = mock();
private StandardWebSocketSession webSocketSession;
private StandardWebSocketSession webSocketSession = new StandardWebSocketSession(null, null, null, null);
private Session session;
private StandardWebSocketHandlerAdapter adapter = new StandardWebSocketHandlerAdapter(this.webSocketHandler, this.webSocketSession);
@BeforeEach
public void setup() {
this.session = mock(Session.class);
this.webSocketHandler = mock(WebSocketHandler.class);
this.webSocketSession = new StandardWebSocketSession(null, null, null, null);
this.adapter = new StandardWebSocketHandlerAdapter(this.webSocketHandler, this.webSocketSession);
}
@Test
public void onOpen() throws Throwable {
void onOpen() throws Throwable {
URI uri = URI.create("https://example.org");
given(this.session.getRequestURI()).willReturn(uri);
this.adapter.onOpen(this.session, null);
@@ -73,13 +64,13 @@ public class StandardWebSocketHandlerAdapterTests {
}
@Test
public void onClose() throws Throwable {
void onClose() throws Throwable {
this.adapter.onClose(this.session, new CloseReason(CloseCodes.NORMAL_CLOSURE, "reason"));
verify(this.webSocketHandler).afterConnectionClosed(this.webSocketSession, CloseStatus.NORMAL.withReason("reason"));
}
@Test
public void onError() throws Throwable {
void onError() throws Throwable {
Exception exception = new Exception();
this.adapter.onError(this.session, exception);
verify(this.webSocketHandler).handleTransportError(this.webSocketSession, exception);

View File

@@ -21,23 +21,23 @@ import java.util.Map;
import jakarta.websocket.Session;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.core.testfixture.security.TestPrincipal;
import org.springframework.http.HttpHeaders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Unit tests for {@link org.springframework.web.socket.adapter.standard.StandardWebSocketSession}.
* Unit tests for {@link StandardWebSocketSession}.
*
* @author Rossen Stoyanchev
*/
@SuppressWarnings("resource")
public class StandardWebSocketSessionTests {
class StandardWebSocketSessionTests {
private final HttpHeaders headers = new HttpHeaders();
@@ -46,7 +46,7 @@ public class StandardWebSocketSessionTests {
@Test
@SuppressWarnings("resource")
public void getPrincipalWithConstructorArg() {
void getPrincipalWithConstructorArg() {
TestPrincipal user = new TestPrincipal("joe");
StandardWebSocketSession session = new StandardWebSocketSession(this.headers, this.attributes, null, null, user);
@@ -54,10 +54,10 @@ public class StandardWebSocketSessionTests {
}
@Test
public void getPrincipalWithNativeSession() {
void getPrincipalWithNativeSession() {
TestPrincipal user = new TestPrincipal("joe");
Session nativeSession = Mockito.mock(Session.class);
Session nativeSession = mock();
given(nativeSession.getUserPrincipal()).willReturn(user);
StandardWebSocketSession session = new StandardWebSocketSession(this.headers, this.attributes, null, null);
@@ -67,8 +67,8 @@ public class StandardWebSocketSessionTests {
}
@Test
public void getPrincipalNone() {
Session nativeSession = Mockito.mock(Session.class);
void getPrincipalNone() {
Session nativeSession = mock();
given(nativeSession.getUserPrincipal()).willReturn(null);
StandardWebSocketSession session = new StandardWebSocketSession(this.headers, this.attributes, null, null);
@@ -81,10 +81,10 @@ public class StandardWebSocketSessionTests {
}
@Test
public void getAcceptedProtocol() {
void getAcceptedProtocol() {
String protocol = "foo";
Session nativeSession = Mockito.mock(Session.class);
Session nativeSession = mock();
given(nativeSession.getNegotiatedSubprotocol()).willReturn(protocol);
StandardWebSocketSession session = new StandardWebSocketSession(this.headers, this.attributes, null, null);
@@ -97,7 +97,7 @@ public class StandardWebSocketSessionTests {
}
@Test // gh-29315
public void addAttributesWithNullKeyOrValue() {
void addAttributesWithNullKeyOrValue() {
this.attributes.put(null, "value");
this.attributes.put("key", null);
this.attributes.put("foo", "bar");

View File

@@ -51,7 +51,7 @@ class StandardWebSocketClientTests {
private final WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
private final WebSocketContainer wsContainer = mock(WebSocketContainer.class);
private final WebSocketContainer wsContainer = mock();
private final StandardWebSocketClient wsClient = new StandardWebSocketClient(this.wsContainer);

View File

@@ -60,7 +60,7 @@ class WebSocketMessageBrokerStatsTests {
@Test
void inboundAndOutboundChannelsWithMockedTaskExecutor() {
TaskExecutor executor = mock(TaskExecutor.class);
TaskExecutor executor = mock();
stats.setInboundChannelExecutor(executor);
stats.setOutboundChannelExecutor(executor);
@@ -82,7 +82,7 @@ class WebSocketMessageBrokerStatsTests {
@Test
void sockJsTaskSchedulerWithMockedTaskScheduler() {
TaskScheduler scheduler = mock(TaskScheduler.class);
TaskScheduler scheduler = mock();
stats.setSockJsTaskScheduler(scheduler);

View File

@@ -48,12 +48,12 @@ public class WebMvcStompEndpointRegistryTests {
@BeforeEach
public void setup() {
SubscribableChannel inChannel = mock(SubscribableChannel.class);
SubscribableChannel outChannel = mock(SubscribableChannel.class);
SubscribableChannel inChannel = mock();
SubscribableChannel outChannel = mock();
this.webSocketHandler = new SubProtocolWebSocketHandler(inChannel, outChannel);
WebSocketTransportRegistration transport = new WebSocketTransportRegistration();
TaskScheduler scheduler = mock(TaskScheduler.class);
TaskScheduler scheduler = mock();
this.endpointRegistry = new WebMvcStompEndpointRegistry(this.webSocketHandler, transport, scheduler);
}
@@ -91,7 +91,7 @@ public class WebMvcStompEndpointRegistryTests {
@Test
public void errorHandler() throws Exception {
StompSubProtocolErrorHandler errorHandler = mock(StompSubProtocolErrorHandler.class);
StompSubProtocolErrorHandler errorHandler = mock();
this.endpointRegistry.setErrorHandler(errorHandler);
this.endpointRegistry.addEndpoint("/stompOverWebSocket");

View File

@@ -21,8 +21,6 @@ import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.util.MultiValueMap;
import org.springframework.web.HttpRequestHandler;
@@ -41,17 +39,15 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Test fixture for
* {@link org.springframework.web.socket.config.annotation.WebMvcStompWebSocketEndpointRegistration}.
* Tests for {@link WebMvcStompWebSocketEndpointRegistration}.
*
* @author Rossen Stoyanchev
*/
class WebMvcStompWebSocketEndpointRegistrationTests {
private final SubProtocolWebSocketHandler handler =
new SubProtocolWebSocketHandler(mock(MessageChannel.class), mock(SubscribableChannel.class));
private final SubProtocolWebSocketHandler handler = new SubProtocolWebSocketHandler(mock(), mock());
private final TaskScheduler scheduler = mock(TaskScheduler.class);
private final TaskScheduler scheduler = mock();
@Test

View File

@@ -46,7 +46,7 @@ public class WebSocketHandlerRegistrationTests {
private TestWebSocketHandlerRegistration registration = new TestWebSocketHandlerRegistration();
private TaskScheduler taskScheduler = mock(TaskScheduler.class);
private TaskScheduler taskScheduler = mock();
@Test

View File

@@ -44,7 +44,6 @@ import org.springframework.messaging.support.AbstractSubscribableChannel;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.ExecutorSubscribableChannel;
import org.springframework.messaging.support.ImmutableMessageChannelInterceptor;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
@@ -239,7 +238,7 @@ class WebSocketMessageBrokerConfigurationSupportTests {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker()
.setTaskScheduler(mock(TaskScheduler.class))
.setTaskScheduler(mock())
.setHeartbeatValue(new long[] {15000, 15000});
}
}

View File

@@ -16,7 +16,6 @@
package org.springframework.web.socket.handler;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.web.socket.CloseStatus;
@@ -32,28 +31,17 @@ import static org.mockito.Mockito.mock;
*
* @author Rossen Stoyanchev
*/
public class ExceptionWebSocketHandlerDecoratorTests {
class ExceptionWebSocketHandlerDecoratorTests {
private TestWebSocketSession session;
private TestWebSocketSession session = new TestWebSocketSession(true);
private ExceptionWebSocketHandlerDecorator decorator;
private WebSocketHandler delegate = mock();
private WebSocketHandler delegate;
private ExceptionWebSocketHandlerDecorator decorator = new ExceptionWebSocketHandlerDecorator(this.delegate);
@BeforeEach
public void setup() {
this.delegate = mock(WebSocketHandler.class);
this.decorator = new ExceptionWebSocketHandlerDecorator(this.delegate);
this.session = new TestWebSocketSession();
this.session.setOpen(true);
}
@Test
public void afterConnectionEstablished() throws Exception {
void afterConnectionEstablished() throws Exception {
willThrow(new IllegalStateException("error"))
.given(this.delegate).afterConnectionEstablished(this.session);
@@ -63,8 +51,7 @@ public class ExceptionWebSocketHandlerDecoratorTests {
}
@Test
public void handleMessage() throws Exception {
void handleMessage() throws Exception {
TextMessage message = new TextMessage("payload");
willThrow(new IllegalStateException("error"))
@@ -76,8 +63,7 @@ public class ExceptionWebSocketHandlerDecoratorTests {
}
@Test
public void handleTransportError() throws Exception {
void handleTransportError() throws Exception {
Exception exception = new Exception("transport error");
willThrow(new IllegalStateException("error"))
@@ -89,8 +75,7 @@ public class ExceptionWebSocketHandlerDecoratorTests {
}
@Test
public void afterConnectionClosed() throws Exception {
void afterConnectionClosed() throws Exception {
CloseStatus closeStatus = CloseStatus.NORMAL;
willThrow(new IllegalStateException("error"))

View File

@@ -69,6 +69,10 @@ public class TestWebSocketSession implements WebSocketSession {
this.id = id;
}
public TestWebSocketSession(boolean open) {
this.open = open;
}
@Override
public String getId() {
return this.id;

View File

@@ -28,7 +28,6 @@ import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
@@ -70,34 +69,30 @@ import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Test fixture for {@link StompSubProtocolHandler} tests.
* Tests for {@link StompSubProtocolHandler}.
*
* @author Rossen Stoyanchev
*/
public class StompSubProtocolHandlerTests {
class StompSubProtocolHandlerTests {
private static final byte[] EMPTY_PAYLOAD = new byte[0];
private StompSubProtocolHandler protocolHandler;
private StompSubProtocolHandler protocolHandler = new StompSubProtocolHandler();
private TestWebSocketSession session;
private TestWebSocketSession session = new TestWebSocketSession();
private MessageChannel channel;
private MessageChannel channel = mock();
@SuppressWarnings("rawtypes")
private ArgumentCaptor<Message> messageCaptor;
private ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
@BeforeEach
void setup() {
this.protocolHandler = new StompSubProtocolHandler();
this.channel = Mockito.mock(MessageChannel.class);
this.messageCaptor = ArgumentCaptor.forClass(Message.class);
given(this.channel.send(any())).willReturn(true);
this.session = new TestWebSocketSession();
this.session.setId("s1");
this.session.setPrincipal(new TestPrincipal("joe"));
given(this.channel.send(any())).willReturn(true);
}
@Test
@@ -234,7 +229,7 @@ public class StompSubProtocolHandlerTests {
@Test
void handleMessageToClientWithHeartbeatSuppressingSockJsHeartbeat() throws IOException {
SockJsSession sockJsSession = Mockito.mock(SockJsSession.class);
SockJsSession sockJsSession = mock();
given(sockJsSession.getId()).willReturn("s1");
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECTED);
accessor.setHeartbeat(0, 10);
@@ -247,7 +242,7 @@ public class StompSubProtocolHandlerTests {
verify(sockJsSession).sendMessage(any(WebSocketMessage.class));
verifyNoMoreInteractions(sockJsSession);
sockJsSession = Mockito.mock(SockJsSession.class);
sockJsSession = mock();
given(sockJsSession.getId()).willReturn("s1");
accessor = StompHeaderAccessor.create(StompCommand.CONNECTED);
accessor.setHeartbeat(0, 0);
@@ -463,7 +458,7 @@ public class StompSubProtocolHandlerTests {
@Test
void eventPublicationWithExceptions() {
ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class);
ApplicationEventPublisher publisher = mock();
this.protocolHandler.setApplicationEventPublisher(publisher);
this.protocolHandler.afterSessionStarted(this.session, this.channel);
@@ -504,7 +499,7 @@ public class StompSubProtocolHandlerTests {
@Test
void webSocketScope() {
Runnable runnable = Mockito.mock(Runnable.class);
Runnable runnable = mock();
SimpAttributes simpAttributes = new SimpAttributes(this.session.getId(), this.session.getAttributes());
simpAttributes.setAttribute("name", "value");
simpAttributes.registerDestructionCallback("name", runnable);

View File

@@ -20,7 +20,6 @@ import java.util.concurrent.ConcurrentHashMap;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.messaging.Message;
@@ -36,9 +35,11 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Unit tests for {@link WebSocketAnnotationMethodMessageHandler}.
*
* @author Rossen Stoyanchev
*/
public class WebSocketAnnotationMethodMessageHandlerTests {
@@ -55,7 +56,7 @@ public class WebSocketAnnotationMethodMessageHandlerTests {
this.applicationContext.registerSingleton("controllerAdvice", TestControllerAdvice.class);
this.applicationContext.refresh();
SubscribableChannel channel = Mockito.mock(SubscribableChannel.class);
SubscribableChannel channel = mock();
SimpMessageSendingOperations brokerTemplate = new SimpMessagingTemplate(channel);
this.messageHandler = new TestWebSocketAnnotationMethodMessageHandler(brokerTemplate, channel, channel);

View File

@@ -67,7 +67,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
* @author Rossen Stoyanchev
*/
@MockitoSettings(strictness = Strictness.LENIENT)
public class WebSocketStompClientTests {
class WebSocketStompClientTests {
@Mock
private TaskScheduler taskScheduler;
@@ -86,8 +86,8 @@ public class WebSocketStompClientTests {
@BeforeEach
public void setUp() throws Exception {
WebSocketClient webSocketClient = mock(WebSocketClient.class);
void setUp() throws Exception {
WebSocketClient webSocketClient = mock();
this.stompClient = new TestWebSocketStompClient(webSocketClient);
this.stompClient.setTaskScheduler(this.taskScheduler);
this.stompClient.setStompSession(this.stompSession);
@@ -100,7 +100,7 @@ public class WebSocketStompClientTests {
@Test
public void webSocketHandshakeFailure() throws Exception {
void webSocketHandshakeFailure() throws Exception {
connect();
IllegalStateException handshakeFailure = new IllegalStateException("simulated exception");
@@ -110,13 +110,13 @@ public class WebSocketStompClientTests {
}
@Test
public void webSocketConnectionEstablished() throws Exception {
void webSocketConnectionEstablished() throws Exception {
connect().afterConnectionEstablished(this.webSocketSession);
verify(this.stompSession).afterConnected(notNull());
}
@Test
public void webSocketTransportError() throws Exception {
void webSocketTransportError() throws Exception {
IllegalStateException exception = new IllegalStateException("simulated exception");
connect().handleTransportError(this.webSocketSession, exception);
@@ -124,14 +124,14 @@ public class WebSocketStompClientTests {
}
@Test
public void webSocketConnectionClosed() throws Exception {
void webSocketConnectionClosed() throws Exception {
connect().afterConnectionClosed(this.webSocketSession, CloseStatus.NORMAL);
verify(this.stompSession).afterConnectionClosed();
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void handleWebSocketMessage() throws Exception {
void handleWebSocketMessage() throws Exception {
String text = "SEND\na:alpha\n\nMessage payload\0";
connect().handleMessage(this.webSocketSession, new TextMessage(text));
@@ -149,7 +149,7 @@ public class WebSocketStompClientTests {
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void handleWebSocketMessageSplitAcrossTwoMessage() throws Exception {
void handleWebSocketMessageSplitAcrossTwoMessage() throws Exception {
WebSocketHandler webSocketHandler = connect();
String part1 = "SEND\na:alpha\n\nMessage";
@@ -174,7 +174,7 @@ public class WebSocketStompClientTests {
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void handleWebSocketMessageBinary() throws Exception {
void handleWebSocketMessageBinary() throws Exception {
String text = "SEND\na:alpha\n\nMessage payload\0";
connect().handleMessage(this.webSocketSession, new BinaryMessage(text.getBytes(StandardCharsets.UTF_8)));
@@ -191,13 +191,13 @@ public class WebSocketStompClientTests {
}
@Test
public void handleWebSocketMessagePong() throws Exception {
void handleWebSocketMessagePong() throws Exception {
connect().handleMessage(this.webSocketSession, new PongMessage());
verifyNoMoreInteractions(this.stompSession);
}
@Test
public void sendWebSocketMessage() throws Exception {
void sendWebSocketMessage() throws Exception {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND);
accessor.setDestination("/topic/foo");
byte[] payload = "payload".getBytes(StandardCharsets.UTF_8);
@@ -212,7 +212,7 @@ public class WebSocketStompClientTests {
}
@Test
public void sendWebSocketBinary() throws Exception {
void sendWebSocketBinary() throws Exception {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND);
accessor.setDestination("/b");
accessor.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM);
@@ -224,12 +224,13 @@ public class WebSocketStompClientTests {
verify(this.webSocketSession).sendMessage(binaryMessageCaptor.capture());
BinaryMessage binaryMessage = binaryMessageCaptor.getValue();
assertThat(binaryMessage).isNotNull();
assertThat(new String(binaryMessage.getPayload().array(), StandardCharsets.UTF_8)).isEqualTo("SEND\ndestination:/b\ncontent-type:application/octet-stream\ncontent-length:7\n\npayload\0");
assertThat(new String(binaryMessage.getPayload().array(), StandardCharsets.UTF_8))
.isEqualTo("SEND\ndestination:/b\ncontent-type:application/octet-stream\ncontent-length:7\n\npayload\0");
}
@Test
public void heartbeatDefaultValue() throws Exception {
WebSocketStompClient stompClient = new WebSocketStompClient(mock(WebSocketClient.class));
void heartbeatDefaultValue() throws Exception {
WebSocketStompClient stompClient = new WebSocketStompClient(mock());
assertThat(stompClient.getDefaultHeartbeat()).isEqualTo(new long[] {0, 0});
StompHeaders connectHeaders = stompClient.processConnectHeaders(null);
@@ -237,9 +238,9 @@ public class WebSocketStompClientTests {
}
@Test
public void heartbeatDefaultValueWithScheduler() throws Exception {
WebSocketStompClient stompClient = new WebSocketStompClient(mock(WebSocketClient.class));
stompClient.setTaskScheduler(mock(TaskScheduler.class));
void heartbeatDefaultValueWithScheduler() throws Exception {
WebSocketStompClient stompClient = new WebSocketStompClient(mock());
stompClient.setTaskScheduler(mock());
assertThat(stompClient.getDefaultHeartbeat()).isEqualTo(new long[] {10000, 10000});
StompHeaders connectHeaders = stompClient.processConnectHeaders(null);
@@ -247,44 +248,44 @@ public class WebSocketStompClientTests {
}
@Test
public void heartbeatDefaultValueSetWithoutScheduler() throws Exception {
WebSocketStompClient stompClient = new WebSocketStompClient(mock(WebSocketClient.class));
void heartbeatDefaultValueSetWithoutScheduler() throws Exception {
WebSocketStompClient stompClient = new WebSocketStompClient(mock());
stompClient.setDefaultHeartbeat(new long[] {5, 5});
assertThatIllegalStateException().isThrownBy(() ->
stompClient.processConnectHeaders(null));
}
@Test
public void readInactivityAfterDelayHasElapsed() throws Exception {
void readInactivityAfterDelayHasElapsed() throws Exception {
TcpConnection<byte[]> tcpConnection = getTcpConnection();
Runnable runnable = mock(Runnable.class);
Runnable runnable = mock();
long delay = 2;
tcpConnection.onReadInactivity(runnable, delay);
testInactivityTaskScheduling(runnable, delay, 10);
}
@Test
public void readInactivityBeforeDelayHasElapsed() throws Exception {
void readInactivityBeforeDelayHasElapsed() throws Exception {
TcpConnection<byte[]> tcpConnection = getTcpConnection();
Runnable runnable = mock(Runnable.class);
Runnable runnable = mock();
long delay = 10000;
tcpConnection.onReadInactivity(runnable, delay);
testInactivityTaskScheduling(runnable, delay, 0);
}
@Test
public void writeInactivityAfterDelayHasElapsed() throws Exception {
void writeInactivityAfterDelayHasElapsed() throws Exception {
TcpConnection<byte[]> tcpConnection = getTcpConnection();
Runnable runnable = mock(Runnable.class);
Runnable runnable = mock();
long delay = 2;
tcpConnection.onWriteInactivity(runnable, delay);
testInactivityTaskScheduling(runnable, delay, 10);
}
@Test
public void writeInactivityBeforeDelayHasElapsed() throws Exception {
void writeInactivityBeforeDelayHasElapsed() throws Exception {
TcpConnection<byte[]> tcpConnection = getTcpConnection();
Runnable runnable = mock(Runnable.class);
Runnable runnable = mock();
long delay = 1000;
tcpConnection.onWriteInactivity(runnable, delay);
testInactivityTaskScheduling(runnable, delay, 0);
@@ -292,14 +293,14 @@ public class WebSocketStompClientTests {
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
public void cancelInactivityTasks() throws Exception {
void cancelInactivityTasks() throws Exception {
TcpConnection<byte[]> tcpConnection = getTcpConnection();
ScheduledFuture future = mock(ScheduledFuture.class);
ScheduledFuture future = mock();
given(this.taskScheduler.scheduleWithFixedDelay(any(), eq(Duration.ofMillis(1)))).willReturn(future);
tcpConnection.onReadInactivity(mock(Runnable.class), 2L);
tcpConnection.onWriteInactivity(mock(Runnable.class), 2L);
tcpConnection.onReadInactivity(mock(), 2L);
tcpConnection.onWriteInactivity(mock(), 2L);
this.webSocketHandlerCaptor.getValue().afterConnectionClosed(this.webSocketSession, CloseStatus.NORMAL);
@@ -309,7 +310,7 @@ public class WebSocketStompClientTests {
private WebSocketHandler connect() {
this.stompClient.connectAsync("/foo", mock(StompSessionHandler.class));
this.stompClient.connectAsync("/foo", mock());
verify(this.stompSession).getSession();
verifyNoMoreInteractions(this.stompSession);
@@ -323,8 +324,8 @@ public class WebSocketStompClientTests {
private TcpConnection<byte[]> getTcpConnection() throws Exception {
WebSocketHandler handler = connect();
handler.afterConnectionEstablished(this.webSocketSession);
if (handler instanceof WebSocketHandlerDecorator) {
handler = ((WebSocketHandlerDecorator) handler).getLastHandler();
if (handler instanceof WebSocketHandlerDecorator handlerDecorator) {
handler = handlerDecorator.getLastHandler();
}
return (TcpConnection<byte[]>) handler;
}
@@ -357,11 +358,11 @@ public class WebSocketStompClientTests {
private ConnectionHandlingStompSession stompSession;
public TestWebSocketStompClient(WebSocketClient webSocketClient) {
TestWebSocketStompClient(WebSocketClient webSocketClient) {
super(webSocketClient);
}
public void setStompSession(ConnectionHandlingStompSession stompSession) {
void setStompSession(ConnectionHandlingStompSession stompSession) {
this.stompSession = stompSession;
}

View File

@@ -43,7 +43,7 @@ import static org.mockito.Mockito.verify;
*/
public class DefaultHandshakeHandlerTests extends AbstractHttpRequestTests {
private RequestUpgradeStrategy upgradeStrategy = mock(RequestUpgradeStrategy.class);
private RequestUpgradeStrategy upgradeStrategy = mock();
private DefaultHandshakeHandler handshakeHandler = new DefaultHandshakeHandler(this.upgradeStrategy);

View File

@@ -34,40 +34,35 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Test fixture for {@link ServerEndpointExporter}.
* Tests for {@link ServerEndpointExporter}.
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
*/
public class ServerEndpointExporterTests {
class ServerEndpointExporterTests {
private ServerContainer serverContainer;
private ServerContainer serverContainer = mock();
private ServletContext servletContext;
private ServletContext servletContext = new MockServletContext();
private ServerEndpointExporter exporter = new ServerEndpointExporter();
private AnnotationConfigWebApplicationContext webAppContext;
private ServerEndpointExporter exporter;
@BeforeEach
public void setup() {
this.serverContainer = mock(ServerContainer.class);
this.servletContext = new MockServletContext();
void setup() {
this.servletContext.setAttribute("jakarta.websocket.server.ServerContainer", this.serverContainer);
this.webAppContext = new AnnotationConfigWebApplicationContext();
this.webAppContext.register(Config.class);
this.webAppContext.setServletContext(this.servletContext);
this.webAppContext.refresh();
this.exporter = new ServerEndpointExporter();
}
@Test
public void addAnnotatedEndpointClasses() throws Exception {
void addAnnotatedEndpointClasses() throws Exception {
this.exporter.setAnnotatedEndpointClasses(AnnotatedDummyEndpoint.class);
this.exporter.setApplicationContext(this.webAppContext);
this.exporter.afterPropertiesSet();
@@ -78,7 +73,7 @@ public class ServerEndpointExporterTests {
}
@Test
public void addAnnotatedEndpointClassesWithServletContextOnly() throws Exception {
void addAnnotatedEndpointClassesWithServletContextOnly() throws Exception {
this.exporter.setAnnotatedEndpointClasses(AnnotatedDummyEndpoint.class, AnnotatedDummyEndpointBean.class);
this.exporter.setServletContext(this.servletContext);
this.exporter.afterPropertiesSet();
@@ -89,7 +84,7 @@ public class ServerEndpointExporterTests {
}
@Test
public void addAnnotatedEndpointClassesWithExplicitServerContainerOnly() throws Exception {
void addAnnotatedEndpointClassesWithExplicitServerContainerOnly() throws Exception {
this.exporter.setAnnotatedEndpointClasses(AnnotatedDummyEndpoint.class, AnnotatedDummyEndpointBean.class);
this.exporter.setServerContainer(this.serverContainer);
this.exporter.afterPropertiesSet();
@@ -100,7 +95,7 @@ public class ServerEndpointExporterTests {
}
@Test
public void addServerEndpointConfigBean() throws Exception {
void addServerEndpointConfigBean() throws Exception {
ServerEndpointRegistration endpointRegistration = new ServerEndpointRegistration("/dummy", new DummyEndpoint());
this.webAppContext.getBeanFactory().registerSingleton("dummyEndpoint", endpointRegistration);
@@ -112,7 +107,7 @@ public class ServerEndpointExporterTests {
}
@Test
public void addServerEndpointConfigBeanWithExplicitServletContext() throws Exception {
void addServerEndpointConfigBeanWithExplicitServletContext() throws Exception {
ServerEndpointRegistration endpointRegistration = new ServerEndpointRegistration("/dummy", new DummyEndpoint());
this.webAppContext.getBeanFactory().registerSingleton("dummyEndpoint", endpointRegistration);
@@ -125,7 +120,7 @@ public class ServerEndpointExporterTests {
}
@Test
public void addServerEndpointConfigBeanWithExplicitServerContainer() throws Exception {
void addServerEndpointConfigBeanWithExplicitServerContainer() throws Exception {
ServerEndpointRegistration endpointRegistration = new ServerEndpointRegistration("/dummy", new DummyEndpoint());
this.webAppContext.getBeanFactory().registerSingleton("dummyEndpoint", endpointRegistration);
this.servletContext.removeAttribute("jakarta.websocket.server.ServerContainer");
@@ -161,7 +156,7 @@ public class ServerEndpointExporterTests {
static class Config {
@Bean
public AnnotatedDummyEndpointBean annotatedEndpoint1() {
AnnotatedDummyEndpointBean annotatedEndpoint1() {
return new AnnotatedDummyEndpointBean();
}
}

View File

@@ -16,12 +16,10 @@
package org.springframework.web.socket.server.support;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.web.socket.AbstractHttpRequestTests;
@@ -34,46 +32,30 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Test fixture for {@link HandshakeInterceptorChain}.
* Tests for {@link HandshakeInterceptorChain}.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
public class HandshakeInterceptorChainTests extends AbstractHttpRequestTests {
class HandshakeInterceptorChainTests extends AbstractHttpRequestTests {
private HandshakeInterceptor i1;
private Map<String, Object> attributes = new HashMap<>();
private HandshakeInterceptor i2;
private HandshakeInterceptor i1 = mock();
private HandshakeInterceptor i2 = mock();
private HandshakeInterceptor i3 = mock();
private HandshakeInterceptor i3;
private WebSocketHandler wsHandler = mock();
private List<HandshakeInterceptor> interceptors;
private WebSocketHandler wsHandler;
private Map<String, Object> attributes;
@Override
@BeforeEach
public void setup() {
super.setup();
i1 = mock(HandshakeInterceptor.class);
i2 = mock(HandshakeInterceptor.class);
i3 = mock(HandshakeInterceptor.class);
interceptors = Arrays.asList(i1, i2, i3);
wsHandler = mock(WebSocketHandler.class);
attributes = new HashMap<>();
}
private HandshakeInterceptorChain chain = new HandshakeInterceptorChain(List.of(i1, i2, i3), wsHandler);
@Test
public void success() throws Exception {
void success() throws Exception {
given(i1.beforeHandshake(request, response, wsHandler, attributes)).willReturn(true);
given(i2.beforeHandshake(request, response, wsHandler, attributes)).willReturn(true);
given(i3.beforeHandshake(request, response, wsHandler, attributes)).willReturn(true);
HandshakeInterceptorChain chain = new HandshakeInterceptorChain(interceptors, wsHandler);
chain.applyBeforeHandshake(request, response, attributes);
verify(i1).beforeHandshake(request, response, wsHandler, attributes);
@@ -83,11 +65,10 @@ public class HandshakeInterceptorChainTests extends AbstractHttpRequestTests {
}
@Test
public void applyBeforeHandshakeWithFalseReturnValue() throws Exception {
void applyBeforeHandshakeWithFalseReturnValue() throws Exception {
given(i1.beforeHandshake(request, response, wsHandler, attributes)).willReturn(true);
given(i2.beforeHandshake(request, response, wsHandler, attributes)).willReturn(false);
HandshakeInterceptorChain chain = new HandshakeInterceptorChain(interceptors, wsHandler);
chain.applyBeforeHandshake(request, response, attributes);
verify(i1).beforeHandshake(request, response, wsHandler, attributes);
@@ -97,8 +78,7 @@ public class HandshakeInterceptorChainTests extends AbstractHttpRequestTests {
}
@Test
public void applyAfterHandshakeOnly() {
HandshakeInterceptorChain chain = new HandshakeInterceptorChain(interceptors, wsHandler);
void applyAfterHandshakeOnly() {
chain.applyAfterHandshake(request, response, null);
verifyNoMoreInteractions(i1, i2, i3);

View File

@@ -38,7 +38,7 @@ import static org.mockito.Mockito.mock;
public class HttpSessionHandshakeInterceptorTests extends AbstractHttpRequestTests {
private final Map<String, Object> attributes = new HashMap<>();
private final WebSocketHandler wsHandler = mock(WebSocketHandler.class);
private final WebSocketHandler wsHandler = mock();
@Test

View File

@@ -43,7 +43,7 @@ import static org.mockito.Mockito.mock;
public class OriginHandshakeInterceptorTests extends AbstractHttpRequestTests {
private final Map<String, Object> attributes = new HashMap<>();
private final WebSocketHandler wsHandler = mock(WebSocketHandler.class);
private final WebSocketHandler wsHandler = mock();
@Test

View File

@@ -23,7 +23,6 @@ import org.junit.jupiter.api.Test;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.testfixture.servlet.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThat;
@@ -34,12 +33,11 @@ import static org.mockito.Mockito.mock;
*
* @author Rossen Stoyanchev
*/
public class WebSocketHandlerMappingTests {
class WebSocketHandlerMappingTests {
@Test
void webSocketHandshakeMatch() throws Exception {
HttpRequestHandler handler = new WebSocketHttpRequestHandler(mock(WebSocketHandler.class));
HttpRequestHandler handler = new WebSocketHttpRequestHandler(mock());
WebSocketHandlerMapping mapping = new WebSocketHandlerMapping();
mapping.setUrlMap(Collections.singletonMap("/path", handler));

View File

@@ -46,17 +46,17 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
* @author Rossen Stoyanchev
* @since 5.1.9
*/
public class WebSocketHttpRequestHandlerTests {
class WebSocketHttpRequestHandlerTests {
private final HandshakeHandler handshakeHandler = mock(HandshakeHandler.class);
private final HandshakeHandler handshakeHandler = mock();
private final WebSocketHttpRequestHandler requestHandler = new WebSocketHttpRequestHandler(mock(WebSocketHandler.class), this.handshakeHandler);
private final WebSocketHttpRequestHandler requestHandler = new WebSocketHttpRequestHandler(mock(), this.handshakeHandler);
private final MockHttpServletResponse response = new MockHttpServletResponse();
@Test
public void success() throws ServletException, IOException {
void success() throws ServletException, IOException {
TestInterceptor interceptor = new TestInterceptor(true);
this.requestHandler.setHandshakeInterceptors(Collections.singletonList(interceptor));
this.requestHandler.handleRequest(new MockHttpServletRequest(), this.response);
@@ -66,7 +66,7 @@ public class WebSocketHttpRequestHandlerTests {
}
@Test
public void failure() {
void failure() {
TestInterceptor interceptor = new TestInterceptor(true);
this.requestHandler.setHandshakeInterceptors(Collections.singletonList(interceptor));
@@ -83,7 +83,7 @@ public class WebSocketHttpRequestHandlerTests {
}
@Test // gh-23179
public void handshakeNotAllowed() throws ServletException, IOException {
void handshakeNotAllowed() throws ServletException, IOException {
TestInterceptor interceptor = new TestInterceptor(false);
this.requestHandler.setHandshakeInterceptors(Collections.singletonList(interceptor));

View File

@@ -43,8 +43,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Unit tests for
* {@link org.springframework.web.socket.sockjs.client.AbstractClientSockJsSession}.
* Unit tests for {@link AbstractClientSockJsSession}.
*
* @author Rossen Stoyanchev
*/
@@ -52,20 +51,18 @@ class ClientSockJsSessionTests {
private static final Jackson2SockJsMessageCodec CODEC = new Jackson2SockJsMessageCodec();
private WebSocketHandler handler = mock();
private CompletableFuture<WebSocketSession> connectFuture = new CompletableFuture<>();
private TestClientSockJsSession session;
private WebSocketHandler handler;
private CompletableFuture<WebSocketSession> connectFuture;
@BeforeEach
void setup() {
SockJsUrlInfo urlInfo = new SockJsUrlInfo(URI.create("https://example.com"));
Transport transport = mock(Transport.class);
Transport transport = mock();
TransportRequest request = new DefaultTransportRequest(urlInfo, null, null, transport, TransportType.XHR, CODEC);
this.handler = mock(WebSocketHandler.class);
this.connectFuture = new CompletableFuture<>();
this.session = new TestClientSockJsSession(request, this.handler, this.connectFuture);
}
@@ -188,16 +185,16 @@ class ClientSockJsSessionTests {
@Test
void closeWithNullStatus() throws Exception {
this.session.handleFrame(SockJsFrame.openFrame().getContent());
assertThatIllegalArgumentException().isThrownBy(() ->
this.session.close(null))
assertThatIllegalArgumentException()
.isThrownBy(() -> this.session.close(null))
.withMessageContaining("Invalid close status");
}
@Test
void closeWithStatusOutOfRange() throws Exception {
this.session.handleFrame(SockJsFrame.openFrame().getContent());
assertThatIllegalArgumentException().isThrownBy(() ->
this.session.close(new CloseStatus(2999, "reason")))
assertThatIllegalArgumentException()
.isThrownBy(() -> this.session.close(new CloseStatus(2999, "reason")))
.withMessageContaining("Invalid close status");
}

View File

@@ -49,23 +49,19 @@ class DefaultTransportRequestTests {
private final Jackson2SockJsMessageCodec CODEC = new Jackson2SockJsMessageCodec();
private CompletableFuture<WebSocketSession> connectFuture;
private BiConsumer<WebSocketSession, Throwable> connectCallback;
private TestTransport webSocketTransport;
private TestTransport xhrTransport;
private CompletableFuture<WebSocketSession> connectFuture = new CompletableFuture<>();
@SuppressWarnings("unchecked")
private BiConsumer<WebSocketSession, Throwable> connectCallback = mock();
private TestTransport webSocketTransport = new TestTransport("WebSocketTestTransport");
private TestTransport xhrTransport = new TestTransport("XhrTestTransport");
@BeforeEach
void setup() {
this.connectCallback = mock(BiConsumer.class);
this.connectFuture = new CompletableFuture<>();
this.connectFuture.whenComplete(this.connectCallback);
this.webSocketTransport = new TestTransport("WebSocketTestTransport");
this.xhrTransport = new TestTransport("XhrTestTransport");
}
@@ -73,7 +69,7 @@ class DefaultTransportRequestTests {
void connect() throws Exception {
DefaultTransportRequest request = createTransportRequest(this.webSocketTransport, TransportType.WEBSOCKET);
request.connect(null, this.connectFuture);
WebSocketSession session = mock(WebSocketSession.class);
WebSocketSession session = mock();
this.webSocketTransport.getConnectCallback().accept(session, null);
assertThat(this.connectFuture.get()).isSameAs(session);
}
@@ -93,15 +89,15 @@ class DefaultTransportRequestTests {
// Transport error => no more fallback
this.xhrTransport.getConnectCallback().accept(null, new IOException("Fake exception 2"));
assertThat(this.connectFuture.isDone()).isTrue();
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
this.connectFuture::get)
assertThatExceptionOfType(ExecutionException.class)
.isThrownBy(this.connectFuture::get)
.withMessageContaining("Fake exception 2");
}
@Test
void fallbackAfterTimeout() {
TaskScheduler scheduler = mock(TaskScheduler.class);
Runnable sessionCleanupTask = mock(Runnable.class);
TaskScheduler scheduler = mock();
Runnable sessionCleanupTask = mock();
DefaultTransportRequest request1 = createTransportRequest(this.webSocketTransport, TransportType.WEBSOCKET);
DefaultTransportRequest request2 = createTransportRequest(this.xhrTransport, TransportType.XHR_STREAMING);
request1.setFallbackRequest(request2);

View File

@@ -70,7 +70,7 @@ class RestTemplateXhrTransportTests {
private static final Jackson2SockJsMessageCodec CODEC = new Jackson2SockJsMessageCodec();
private final WebSocketHandler webSocketHandler = mock(WebSocketHandler.class);
private final WebSocketHandler webSocketHandler = mock();
@Test
@@ -132,7 +132,7 @@ class RestTemplateXhrTransportTests {
@SuppressWarnings("deprecation")
void connectFailure() {
final HttpServerErrorException expected = new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR);
RestOperations restTemplate = mock(RestOperations.class);
RestOperations restTemplate = mock();
given(restTemplate.execute((URI) any(), eq(HttpMethod.POST), any(), any())).willThrow(expected);
final CountDownLatch latch = new CountDownLatch(1);
@@ -201,7 +201,7 @@ class RestTemplateXhrTransportTests {
}
private ClientHttpResponse response(HttpStatus status, String body) throws IOException {
ClientHttpResponse response = mock(ClientHttpResponse.class);
ClientHttpResponse response = mock();
InputStream inputStream = getInputStream(body);
given(response.getStatusCode()).willReturn(status);
given(response.getBody()).willReturn(inputStream);

View File

@@ -49,18 +49,17 @@ class SockJsClientTests {
private static final String URL = "https://example.com";
private static final WebSocketHandler handler = mock(WebSocketHandler.class);
private static final WebSocketHandler handler = mock();
private final InfoReceiver infoReceiver = mock(InfoReceiver.class);
private final InfoReceiver infoReceiver = mock();
private final TestTransport webSocketTransport = new TestTransport("WebSocketTestTransport");
private final XhrTestTransport xhrTransport = new XhrTestTransport("XhrTestTransport");
@SuppressWarnings({ "deprecation", "unchecked" })
private org.springframework.util.concurrent.ListenableFutureCallback<WebSocketSession> connectCallback =
mock(org.springframework.util.concurrent.ListenableFutureCallback.class);
private org.springframework.util.concurrent.ListenableFutureCallback<WebSocketSession> connectCallback = mock();
private SockJsClient sockJsClient = new SockJsClient(List.of(this.webSocketTransport, this.xhrTransport));
@@ -76,7 +75,7 @@ class SockJsClientTests {
setupInfoRequest(true);
this.sockJsClient.doHandshake(handler, URL).addCallback(this.connectCallback);
assertThat(this.webSocketTransport.invoked()).isTrue();
WebSocketSession session = mock(WebSocketSession.class);
WebSocketSession session = mock();
this.webSocketTransport.getConnectCallback().accept(session, null);
verify(this.connectCallback).onSuccess(session);
verifyNoMoreInteractions(this.connectCallback);

View File

@@ -79,7 +79,7 @@ class TestTransport implements Transport {
@Override
public CompletableFuture<WebSocketSession> connectAsync(TransportRequest request, WebSocketHandler handler) {
this.request = request;
this.future = mock(CompletableFuture.class);
this.future = mock();
return this.future;
}

View File

@@ -89,13 +89,13 @@ class XhrTransportTests {
HttpHeaders handshakeHeaders = new HttpHeaders();
handshakeHeaders.setOrigin("foo");
TransportRequest request = mock(TransportRequest.class);
TransportRequest request = mock();
given(request.getSockJsUrlInfo()).willReturn(new SockJsUrlInfo(URI.create("https://example.com")));
given(request.getHandshakeHeaders()).willReturn(handshakeHeaders);
given(request.getHttpRequestHeaders()).willReturn(new HttpHeaders());
TestXhrTransport transport = new TestXhrTransport();
WebSocketHandler handler = mock(WebSocketHandler.class);
WebSocketHandler handler = mock();
transport.connect(request, handler);
ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);

View File

@@ -140,8 +140,8 @@ class SockJsServiceTests extends AbstractHttpRequestTests {
@Test // SPR-11919
void handleInfoGetWildflyNPE() throws IOException {
HttpServletResponse mockResponse = mock(HttpServletResponse.class);
ServletOutputStream ous = mock(ServletOutputStream.class);
HttpServletResponse mockResponse = mock();
ServletOutputStream ous = mock();
given(mockResponse.getHeaders(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).willThrow(NullPointerException.class);
given(mockResponse.getOutputStream()).willReturn(ous);
this.response = new ServletServerHttpResponse(mockResponse);

View File

@@ -60,7 +60,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
* @author Ben Kiefer
*/
@MockitoSettings(strictness = Strictness.LENIENT)
public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
private static final String sockJsPrefix = "/mysockjs";
@@ -107,8 +107,8 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
@Test
public void defaultTransportHandlers() {
DefaultSockJsService service = new DefaultSockJsService(mock(TaskScheduler.class));
void defaultTransportHandlers() {
DefaultSockJsService service = new DefaultSockJsService(mock());
Map<TransportType, TransportHandler> handlers = service.getTransportHandlers();
assertThat(handlers).hasSize(6);
@@ -121,10 +121,10 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
}
@Test
public void defaultTransportHandlersWithOverride() {
void defaultTransportHandlersWithOverride() {
XhrReceivingTransportHandler xhrHandler = new XhrReceivingTransportHandler();
DefaultSockJsService service = new DefaultSockJsService(mock(TaskScheduler.class), xhrHandler);
DefaultSockJsService service = new DefaultSockJsService(mock(), xhrHandler);
Map<TransportType, TransportHandler> handlers = service.getTransportHandlers();
assertThat(handlers).hasSize(6);
@@ -132,22 +132,22 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
}
@Test
public void invalidAllowedOrigins() {
void invalidAllowedOrigins() {
assertThatIllegalArgumentException().isThrownBy(() ->
this.service.setAllowedOrigins(null));
}
@Test
public void customizedTransportHandlerList() {
void customizedTransportHandlerList() {
TransportHandlingSockJsService service = new TransportHandlingSockJsService(
mock(TaskScheduler.class), new XhrPollingTransportHandler(), new XhrReceivingTransportHandler());
mock(), new XhrPollingTransportHandler(), new XhrReceivingTransportHandler());
Map<TransportType, TransportHandler> actualHandlers = service.getTransportHandlers();
assertThat(actualHandlers).hasSize(2);
}
@Test
public void handleTransportRequestXhr() throws Exception {
void handleTransportRequestXhr() throws Exception {
String sockJsPath = sessionUrlPrefix + "xhr";
setRequest("POST", sockJsPrefix + sockJsPath);
this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler);
@@ -162,7 +162,7 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
}
@Test // SPR-12226
public void handleTransportRequestXhrAllowedOriginsMatch() throws Exception {
void handleTransportRequestXhrAllowedOriginsMatch() throws Exception {
String sockJsPath = sessionUrlPrefix + "xhr";
setRequest("POST", sockJsPrefix + sockJsPath);
this.service.setAllowedOrigins(Arrays.asList("https://mydomain1.example", "https://mydomain2.example"));
@@ -173,7 +173,7 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
}
@Test // SPR-12226
public void handleTransportRequestXhrAllowedOriginsNoMatch() throws Exception {
void handleTransportRequestXhrAllowedOriginsNoMatch() throws Exception {
String sockJsPath = sessionUrlPrefix + "xhr";
setRequest("POST", sockJsPrefix + sockJsPath);
this.service.setAllowedOrigins(Arrays.asList("https://mydomain1.example", "https://mydomain2.example"));
@@ -184,7 +184,7 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
}
@Test // SPR-13464
public void handleTransportRequestXhrSameOrigin() throws Exception {
void handleTransportRequestXhrSameOrigin() throws Exception {
String sockJsPath = sessionUrlPrefix + "xhr";
setRequest("POST", sockJsPrefix + sockJsPath);
this.service.setAllowedOrigins(List.of("https://mydomain1.example"));
@@ -196,7 +196,7 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
}
@Test // SPR-13545
public void handleInvalidTransportType() throws Exception {
void handleInvalidTransportType() throws Exception {
String sockJsPath = sessionUrlPrefix + "invalid";
setRequest("POST", sockJsPrefix + sockJsPath);
this.service.setAllowedOrigins(List.of("https://mydomain1.example"));
@@ -208,7 +208,7 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
}
@Test
public void handleTransportRequestXhrOptions() throws Exception {
void handleTransportRequestXhrOptions() throws Exception {
String sockJsPath = sessionUrlPrefix + "xhr";
setRequest("OPTIONS", sockJsPrefix + sockJsPath);
this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler);
@@ -220,7 +220,7 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
}
@Test
public void handleTransportRequestNoSuitableHandler() throws Exception {
void handleTransportRequestNoSuitableHandler() throws Exception {
String sockJsPath = sessionUrlPrefix + "eventsource";
setRequest("POST", sockJsPrefix + sockJsPath);
this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler);
@@ -229,7 +229,7 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
}
@Test
public void handleTransportRequestXhrSend() throws Exception {
void handleTransportRequestXhrSend() throws Exception {
String sockJsPath = sessionUrlPrefix + "xhr_send";
setRequest("POST", sockJsPrefix + sockJsPath);
this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler);
@@ -258,7 +258,7 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
}
@Test
public void handleTransportRequestXhrSendWithDifferentUser() throws Exception {
void handleTransportRequestXhrSendWithDifferentUser() throws Exception {
String sockJsPath = sessionUrlPrefix + "xhr";
setRequest("POST", sockJsPrefix + sockJsPath);
this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler);
@@ -281,7 +281,7 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
}
@Test
public void handleTransportRequestWebsocket() throws Exception {
void handleTransportRequestWebsocket() throws Exception {
TransportHandlingSockJsService wsService = new TransportHandlingSockJsService(
this.taskScheduler, this.wsTransportHandler);
String sockJsPath = "/websocket";
@@ -306,7 +306,7 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
}
@Test
public void handleTransportRequestIframe() throws Exception {
void handleTransportRequestIframe() throws Exception {
String sockJsPath = "/iframe.html";
setRequest("GET", sockJsPrefix + sockJsPath);
this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler);

View File

@@ -62,7 +62,7 @@ class HttpReceivingTransportHandlerTests extends AbstractHttpRequestTests {
@Test
void readMessagesNoSession() throws Exception {
WebSocketHandler webSocketHandler = mock(WebSocketHandler.class);
WebSocketHandler webSocketHandler = mock();
assertThatIllegalArgumentException().isThrownBy(() ->
new XhrReceivingTransportHandler().handleRequest(this.request, this.response, webSocketHandler, null));
}
@@ -72,7 +72,7 @@ class HttpReceivingTransportHandlerTests extends AbstractHttpRequestTests {
StubSockJsServiceConfig sockJsConfig = new StubSockJsServiceConfig();
this.servletRequest.setContent("[\"x\"]".getBytes(UTF_8));
WebSocketHandler wsHandler = mock(WebSocketHandler.class);
WebSocketHandler wsHandler = mock();
TestHttpSockJsSession session = new TestHttpSockJsSession("1", sockJsConfig, wsHandler, null);
session.delegateConnectionEstablished();
@@ -87,7 +87,7 @@ class HttpReceivingTransportHandlerTests extends AbstractHttpRequestTests {
private void handleRequest(AbstractHttpReceivingTransportHandler transportHandler) throws Exception {
WebSocketHandler wsHandler = mock(WebSocketHandler.class);
WebSocketHandler wsHandler = mock();
AbstractSockJsSession session = new TestHttpSockJsSession("1", new StubSockJsServiceConfig(), wsHandler, null);
transportHandler.initialize(new StubSockJsServiceConfig());
@@ -100,7 +100,7 @@ class HttpReceivingTransportHandlerTests extends AbstractHttpRequestTests {
private void handleRequestAndExpectFailure() throws Exception {
resetResponse();
WebSocketHandler wsHandler = mock(WebSocketHandler.class);
WebSocketHandler wsHandler = mock();
AbstractSockJsSession session = new TestHttpSockJsSession("1", new StubSockJsServiceConfig(), wsHandler, null);
new XhrReceivingTransportHandler().handleRequest(this.request, this.response, wsHandler, session);

View File

@@ -42,22 +42,18 @@ import static org.mockito.Mockito.verify;
*/
class HttpSendingTransportHandlerTests extends AbstractHttpRequestTests {
private WebSocketHandler webSocketHandler;
private WebSocketHandler webSocketHandler = mock();
private StubSockJsServiceConfig sockJsConfig;
private TaskScheduler taskScheduler = mock();
private TaskScheduler taskScheduler;
private StubSockJsServiceConfig sockJsConfig = new StubSockJsServiceConfig();
@Override
@BeforeEach
@Override
protected void setup() {
super.setup();
this.webSocketHandler = mock(WebSocketHandler.class);
this.taskScheduler = mock(TaskScheduler.class);
this.sockJsConfig = new StubSockJsServiceConfig();
this.sockJsConfig.setTaskScheduler(this.taskScheduler);
setRequest("POST", "/");

View File

@@ -40,12 +40,12 @@ public class SockJsWebSocketHandlerTests {
@Test
public void getSubProtocols() throws Exception {
SubscribableChannel channel = mock(SubscribableChannel.class);
SubscribableChannel channel = mock();
SubProtocolWebSocketHandler handler = new SubProtocolWebSocketHandler(channel, channel);
StompSubProtocolHandler stompHandler = new StompSubProtocolHandler();
handler.addProtocolHandler(stompHandler);
TaskScheduler scheduler = mock(TaskScheduler.class);
TaskScheduler scheduler = mock();
DefaultSockJsService service = new DefaultSockJsService(scheduler);
WebSocketServerSockJsSession session = new WebSocketServerSockJsSession("1", service, handler, null);
SockJsWebSocketHandler sockJsHandler = new SockJsWebSocketHandler(service, handler, session);
@@ -56,7 +56,7 @@ public class SockJsWebSocketHandlerTests {
@Test
public void getSubProtocolsNone() throws Exception {
WebSocketHandler handler = new TextWebSocketHandler();
TaskScheduler scheduler = mock(TaskScheduler.class);
TaskScheduler scheduler = mock();
DefaultSockJsService service = new DefaultSockJsService(scheduler);
WebSocketServerSockJsSession session = new WebSocketServerSockJsSession("1", service, handler, null);
SockJsWebSocketHandler sockJsHandler = new SockJsWebSocketHandler(service, handler, session);

View File

@@ -31,9 +31,9 @@ import static org.mockito.Mockito.mock;
*/
abstract class AbstractSockJsSessionTests<S extends AbstractSockJsSession> {
protected WebSocketHandler webSocketHandler = mock(WebSocketHandler.class);
protected WebSocketHandler webSocketHandler = mock();
protected TaskScheduler taskScheduler = mock(TaskScheduler.class);
protected TaskScheduler taskScheduler = mock();
protected StubSockJsServiceConfig sockJsConfig = new StubSockJsServiceConfig();

View File

@@ -281,7 +281,7 @@ class SockJsSessionTests extends AbstractSockJsSessionTests<TestSockJsSession> {
@Test
void scheduleAndCancelHeartbeat() {
ScheduledFuture<?> task = mock(ScheduledFuture.class);
ScheduledFuture<?> task = mock();
willReturn(task).given(this.taskScheduler).schedule(any(Runnable.class), any(Instant.class));
this.session.setActive(true);