Migrate exception checking tests to use AssertJ

Migrate tests that use `@Test(expectedException=...)` or
`try...fail...catch` to use AssertJ's `assertThatException`
instead.
This commit is contained in:
Phillip Webb
2019-05-20 10:34:51 -07:00
parent fb26fc3f94
commit 02850f357f
561 changed files with 6592 additions and 10389 deletions

View File

@@ -35,6 +35,7 @@ import org.springframework.web.socket.WebSocketHttpHeaders;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
@@ -85,10 +86,11 @@ public class StandardWebSocketClientTests {
assertEquals(443, session.getLocalAddress().getPort());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testGetLocalAddressNoScheme() throws Exception {
URI uri = new URI("localhost/abc");
this.wsClient.doHandshake(this.wsHandler, this.headers, uri);
assertThatIllegalArgumentException().isThrownBy(() ->
this.wsClient.doHandshake(this.wsHandler, this.headers, uri));
}
@Test

View File

@@ -90,6 +90,7 @@ import org.springframework.web.socket.sockjs.transport.TransportType;
import org.springframework.web.socket.sockjs.transport.handler.DefaultSockJsService;
import org.springframework.web.socket.sockjs.transport.handler.WebSocketTransportHandler;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.instanceOf;
@@ -99,7 +100,6 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Test fixture for {@link MessageBrokerBeanDefinitionParser}.
@@ -229,13 +229,8 @@ public class MessageBrokerBeanDefinitionParserTests {
subscriberTypes = Arrays.asList(SimpleBrokerMessageHandler.class, UserDestinationMessageHandler.class);
testChannel("brokerChannel", subscriberTypes, 1);
try {
this.appContext.getBean("brokerChannelExecutor", ThreadPoolTaskExecutor.class);
fail("expected exception");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
this.appContext.getBean("brokerChannelExecutor", ThreadPoolTaskExecutor.class));
assertNotNull(this.appContext.getBean("webSocketScopeConfigurer", CustomScopeConfigurer.class));
@@ -298,13 +293,8 @@ public class MessageBrokerBeanDefinitionParserTests {
subscriberTypes = Arrays.asList(StompBrokerRelayMessageHandler.class, UserDestinationMessageHandler.class);
testChannel("brokerChannel", subscriberTypes, 1);
try {
this.appContext.getBean("brokerChannelExecutor", ThreadPoolTaskExecutor.class);
fail("expected exception");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
this.appContext.getBean("brokerChannelExecutor", ThreadPoolTaskExecutor.class));
String destination = "/topic/unresolved-user-destination";
UserDestinationMessageHandler userDestHandler = this.appContext.getBean(UserDestinationMessageHandler.class);

View File

@@ -25,6 +25,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertNotNull;
/**
@@ -57,13 +58,14 @@ public class BeanCreatingHandlerProviderTests {
assertNotNull(provider.getHandler());
}
@Test(expected = BeanInstantiationException.class)
@Test
public void getHandlerNoBeanFactory() {
BeanCreatingHandlerProvider<EchoHandler> provider =
new BeanCreatingHandlerProvider<>(EchoHandler.class);
provider.getHandler();
assertThatExceptionOfType(BeanInstantiationException.class).isThrownBy(
provider::getHandler);
}

View File

@@ -30,9 +30,10 @@ import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator.OverflowStrategy;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for {@link ConcurrentWebSocketSessionDecorator}.
@@ -100,17 +101,11 @@ public class ConcurrentWebSocketSessionDecoratorTests {
// Exceed send time..
Thread.sleep(200);
try {
TextMessage payload = new TextMessage("payload");
decorator.sendMessage(payload);
fail("Expected exception");
}
catch (SessionLimitExceededException ex) {
String actual = ex.getMessage();
String regex = "Send time [\\d]+ \\(ms\\) for session '123' exceeded the allowed limit 100";
assertTrue("Unexpected message: " + actual, actual.matches(regex));
assertEquals(CloseStatus.SESSION_NOT_RELIABLE, ex.getStatus());
}
TextMessage payload = new TextMessage("payload");
assertThatExceptionOfType(SessionLimitExceededException.class).isThrownBy(() ->
decorator.sendMessage(payload))
.withMessageMatching("Send time [\\d]+ \\(ms\\) for session '123' exceeded the allowed limit 100")
.satisfies(ex -> assertThat(ex.getStatus()).isEqualTo(CloseStatus.SESSION_NOT_RELIABLE));
}
@Test
@@ -136,16 +131,10 @@ public class ConcurrentWebSocketSessionDecoratorTests {
assertEquals(1023, decorator.getBufferSize());
assertTrue(session.isOpen());
try {
decorator.sendMessage(message);
fail("Expected exception");
}
catch (SessionLimitExceededException ex) {
String actual = ex.getMessage();
String regex = "Buffer size [\\d]+ bytes for session '123' exceeds the allowed limit 1024";
assertTrue("Unexpected message: " + actual, actual.matches(regex));
assertEquals(CloseStatus.SESSION_NOT_RELIABLE, ex.getStatus());
}
assertThatExceptionOfType(SessionLimitExceededException.class).isThrownBy(() ->
decorator.sendMessage(message))
.withMessageMatching("Buffer size [\\d]+ bytes for session '123' exceeds the allowed limit 1024")
.satisfies(ex -> assertThat(ex.getStatus()).isEqualTo(CloseStatus.SESSION_NOT_RELIABLE));
}
@Test // SPR-17140

View File

@@ -32,6 +32,7 @@ import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator;
import org.springframework.web.socket.handler.TestWebSocketSession;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
@@ -100,13 +101,14 @@ public class SubProtocolWebSocketHandlerTests {
isA(ConcurrentWebSocketSessionDecorator.class), eq(this.inClientChannel));
}
@Test(expected = IllegalStateException.class)
@Test
public void subProtocolNoMatch() throws Exception {
this.webSocketHandler.setDefaultProtocolHandler(defaultHandler);
this.webSocketHandler.setProtocolHandlers(Arrays.asList(stompHandler, mqttHandler));
this.session.setAcceptedProtocol("wamp");
this.webSocketHandler.afterConnectionEstablished(session);
assertThatIllegalStateException().isThrownBy(() ->
this.webSocketHandler.afterConnectionEstablished(session));
}
@Test
@@ -141,16 +143,18 @@ public class SubProtocolWebSocketHandlerTests {
isA(ConcurrentWebSocketSessionDecorator.class), eq(this.inClientChannel));
}
@Test(expected = IllegalStateException.class)
@Test
public void noSubProtocolTwoHandlers() throws Exception {
this.webSocketHandler.setProtocolHandlers(Arrays.asList(stompHandler, mqttHandler));
this.webSocketHandler.afterConnectionEstablished(session);
assertThatIllegalStateException().isThrownBy(() ->
this.webSocketHandler.afterConnectionEstablished(session));
}
@Test(expected = IllegalStateException.class)
@Test
public void noSubProtocolNoDefaultHandler() throws Exception {
this.webSocketHandler.setProtocolHandlers(Arrays.asList(stompHandler, mqttHandler));
this.webSocketHandler.afterConnectionEstablished(session);
assertThatIllegalStateException().isThrownBy(() ->
this.webSocketHandler.afterConnectionEstablished(session));
}
@Test

View File

@@ -46,10 +46,10 @@ import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.WebSocketClient;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.notNull;
@@ -252,13 +252,8 @@ public class WebSocketStompClientTests {
public void heartbeatDefaultValueSetWithoutScheduler() throws Exception {
WebSocketStompClient stompClient = new WebSocketStompClient(mock(WebSocketClient.class));
stompClient.setDefaultHeartbeat(new long[] {5, 5});
try {
stompClient.processConnectHeaders(null);
fail("Expected IllegalStateException");
}
catch (IllegalStateException ex) {
// ignore
}
assertThatIllegalStateException().isThrownBy(() ->
stompClient.processConnectHeaders(null));
}
@Test

View File

@@ -32,6 +32,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.web.socket.AbstractHttpRequestTests;
import org.springframework.web.socket.WebSocketHandler;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
@@ -44,9 +45,10 @@ import static org.junit.Assert.assertTrue;
*/
public class OriginHandshakeInterceptorTests extends AbstractHttpRequestTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void invalidInput() {
new OriginHandshakeInterceptor(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new OriginHandshakeInterceptor(null));
}
@Test

View File

@@ -31,6 +31,7 @@ import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -54,11 +55,12 @@ public class XhrTransportTests {
assertEquals("body", transport.executeInfoRequest(new URI("https://example.com/info"), null));
}
@Test(expected = HttpServerErrorException.class)
@Test
public void infoResponseError() throws Exception {
TestXhrTransport transport = new TestXhrTransport();
transport.infoResponseToReturn = new ResponseEntity<>("body", HttpStatus.BAD_REQUEST);
assertEquals("body", transport.executeInfoRequest(new URI("https://example.com/info"), null));
assertThatExceptionOfType(HttpServerErrorException.class).isThrownBy(() ->
transport.executeInfoRequest(new URI("https://example.com/info"), null));
}
@Test
@@ -75,12 +77,13 @@ public class XhrTransportTests {
assertEquals(MediaType.APPLICATION_JSON, transport.actualSendRequestHeaders.getContentType());
}
@Test(expected = HttpServerErrorException.class)
@Test
public void sendMessageError() throws Exception {
TestXhrTransport transport = new TestXhrTransport();
transport.sendMessageResponseToReturn = new ResponseEntity<>(HttpStatus.BAD_REQUEST);
URI url = new URI("https://example.com");
transport.executeSendRequest(url, new HttpHeaders(), new TextMessage("payload"));
assertThatExceptionOfType(HttpServerErrorException.class).isThrownBy(() ->
transport.executeSendRequest(url, new HttpHeaders(), new TextMessage("payload")));
}
@Test

View File

@@ -40,6 +40,7 @@ import org.springframework.web.socket.sockjs.transport.TransportType;
import org.springframework.web.socket.sockjs.transport.session.StubSockJsServiceConfig;
import org.springframework.web.socket.sockjs.transport.session.TestSockJsSession;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
@@ -126,9 +127,10 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
assertSame(xhrHandler, handlers.get(xhrHandler.getTransportType()));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void invalidAllowedOrigins() {
this.service.setAllowedOrigins(null);
assertThatIllegalArgumentException().isThrownBy(() ->
this.service.setAllowedOrigins(null));
}
@Test

View File

@@ -26,9 +26,10 @@ import org.springframework.web.socket.sockjs.transport.session.AbstractSockJsSes
import org.springframework.web.socket.sockjs.transport.session.StubSockJsServiceConfig;
import org.springframework.web.socket.sockjs.transport.session.TestHttpSockJsSession;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -59,10 +60,11 @@ public class HttpReceivingTransportHandlerTests extends AbstractHttpRequestTests
handleRequestAndExpectFailure();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void readMessagesNoSession() throws Exception {
WebSocketHandler webSocketHandler = mock(WebSocketHandler.class);
new XhrReceivingTransportHandler().handleRequest(this.request, this.response, webSocketHandler, null);
assertThatIllegalArgumentException().isThrownBy(() ->
new XhrReceivingTransportHandler().handleRequest(this.request, this.response, webSocketHandler, null));
}
@Test
@@ -76,15 +78,11 @@ public class HttpReceivingTransportHandlerTests extends AbstractHttpRequestTests
willThrow(new Exception()).given(wsHandler).handleMessage(session, new TextMessage("x"));
try {
XhrReceivingTransportHandler transportHandler = new XhrReceivingTransportHandler();
transportHandler.initialize(sockJsConfig);
transportHandler.handleRequest(this.request, this.response, wsHandler, session);
fail("Expected exception");
}
catch (SockJsMessageDeliveryException ex) {
assertNull(session.getCloseStatus());
}
XhrReceivingTransportHandler transportHandler = new XhrReceivingTransportHandler();
transportHandler.initialize(sockJsConfig);
assertThatExceptionOfType(SockJsMessageDeliveryException.class).isThrownBy(() ->
transportHandler.handleRequest(this.request, this.response, wsHandler, session));
assertNull(session.getCloseStatus());
}

View File

@@ -31,10 +31,11 @@ import org.springframework.web.socket.sockjs.SockJsMessageDeliveryException;
import org.springframework.web.socket.sockjs.SockJsTransportFailureException;
import org.springframework.web.socket.sockjs.frame.SockJsFrame;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willReturn;
@@ -118,18 +119,14 @@ public class SockJsSessionTests extends AbstractSockJsSessionTests<TestSockJsSes
willThrow(new IOException()).given(this.webSocketHandler).handleMessage(sockJsSession, new TextMessage(msg2));
sockJsSession.delegateConnectionEstablished();
try {
sockJsSession.delegateMessages(msg1, msg2, msg3);
fail("expected exception");
}
catch (SockJsMessageDeliveryException ex) {
assertEquals(Collections.singletonList(msg3), ex.getUndeliveredMessages());
verify(this.webSocketHandler).afterConnectionEstablished(sockJsSession);
verify(this.webSocketHandler).handleMessage(sockJsSession, new TextMessage(msg1));
verify(this.webSocketHandler).handleMessage(sockJsSession, new TextMessage(msg2));
verify(this.webSocketHandler).afterConnectionClosed(sockJsSession, CloseStatus.SERVER_ERROR);
verifyNoMoreInteractions(this.webSocketHandler);
}
assertThatExceptionOfType(SockJsMessageDeliveryException.class).isThrownBy(() ->
sockJsSession.delegateMessages(msg1, msg2, msg3))
.satisfies(ex -> assertThat(ex.getUndeliveredMessages()).containsExactly(msg3));
verify(this.webSocketHandler).afterConnectionEstablished(sockJsSession);
verify(this.webSocketHandler).handleMessage(sockJsSession, new TextMessage(msg1));
verify(this.webSocketHandler).handleMessage(sockJsSession, new TextMessage(msg2));
verify(this.webSocketHandler).afterConnectionClosed(sockJsSession, CloseStatus.SERVER_ERROR);
verifyNoMoreInteractions(this.webSocketHandler);
}
@Test
@@ -237,14 +234,10 @@ public class SockJsSessionTests extends AbstractSockJsSessionTests<TestSockJsSes
this.session.setExceptionOnWrite(new IOException());
this.session.delegateConnectionEstablished();
try {
this.session.writeFrame(SockJsFrame.openFrame());
fail("expected exception");
}
catch (SockJsTransportFailureException ex) {
assertEquals(CloseStatus.SERVER_ERROR, this.session.getCloseStatus());
verify(this.webSocketHandler).afterConnectionClosed(this.session, CloseStatus.SERVER_ERROR);
}
assertThatExceptionOfType(SockJsTransportFailureException.class).isThrownBy(() ->
this.session.writeFrame(SockJsFrame.openFrame()));
assertEquals(CloseStatus.SERVER_ERROR, this.session.getCloseStatus());
verify(this.webSocketHandler).afterConnectionClosed(this.session, CloseStatus.SERVER_ERROR);
}
@Test