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

@@ -26,6 +26,7 @@ import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
/**
@@ -80,19 +81,22 @@ public class ContentDispositionTests {
.filename("中文.txt", StandardCharsets.UTF_8).build(), disposition);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void parseEmpty() {
ContentDisposition.parse("");
assertThatIllegalArgumentException().isThrownBy(() ->
ContentDisposition.parse(""));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void parseNoType() {
ContentDisposition.parse(";");
assertThatIllegalArgumentException().isThrownBy(() ->
ContentDisposition.parse(";"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void parseInvalidParameter() {
ContentDisposition.parse("foo;bar");
assertThatIllegalArgumentException().isThrownBy(() ->
ContentDisposition.parse("foo;bar"));
}
@Test
@@ -147,12 +151,13 @@ public class ContentDispositionTests {
assertEquals("UTF-8''%E4%B8%AD%E6%96%87.txt", result);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void encodeHeaderFieldParamInvalidCharset() {
Method encode = ReflectionUtils.findMethod(ContentDisposition.class,
"encodeHeaderFieldParam", String.class, Charset.class);
ReflectionUtils.makeAccessible(encode);
ReflectionUtils.invokeMethod(encode, null, "test", StandardCharsets.UTF_16);
assertThatIllegalArgumentException().isThrownBy(() ->
ReflectionUtils.invokeMethod(encode, null, "test", StandardCharsets.UTF_16));
}
@Test // SPR-14408
@@ -168,12 +173,13 @@ public class ContentDispositionTests {
assertEquals("中文.txt", result);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void decodeHeaderFieldParamInvalidCharset() {
Method decode = ReflectionUtils.findMethod(ContentDisposition.class,
"decodeHeaderFieldParam", String.class);
ReflectionUtils.makeAccessible(decode);
ReflectionUtils.invokeMethod(decode, null, "UTF-16''test");
assertThatIllegalArgumentException().isThrownBy(() ->
ReflectionUtils.invokeMethod(decode, null, "UTF-16''test"));
}
}

View File

@@ -37,6 +37,7 @@ import java.util.TimeZone;
import org.hamcrest.Matchers;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
@@ -178,12 +179,11 @@ public class HttpHeadersTests {
assertEquals("Invalid Host header", "[::1]", headers.getFirst("Host"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void illegalETag() {
String eTag = "v2.6";
headers.setETag(eTag);
assertEquals("Invalid ETag header", eTag, headers.getETag());
assertEquals("Invalid ETag header", "\"v2.6\"", headers.getFirst("ETag"));
assertThatIllegalArgumentException().isThrownBy(() ->
headers.setETag(eTag));
}
@Test
@@ -194,10 +194,11 @@ public class HttpHeadersTests {
assertEquals("Invalid If-Match header", "\"v2.6\"", headers.getFirst("If-Match"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void ifMatchIllegalHeader() {
headers.setIfMatch("Illegal");
headers.getIfMatch();
assertThatIllegalArgumentException().isThrownBy(
headers::getIfMatch);
}
@Test
@@ -251,10 +252,11 @@ public class HttpHeadersTests {
assertEquals("Invalid Date header", date, headers.getDate());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void dateInvalid() {
headers.set("Date", "Foo Bar Baz");
headers.getDate();
assertThatIllegalArgumentException().isThrownBy(
headers::getDate);
}
@Test
@@ -549,11 +551,12 @@ public class HttpHeadersTests {
assertEquals("foo:bar", new String(result, StandardCharsets.ISO_8859_1));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void basicAuthIllegalChar() {
String username = "foo";
String password = "\u03BB";
headers.setBasicAuth(username, password);
assertThatIllegalArgumentException().isThrownBy(() ->
headers.setBasicAuth(username, password));
}
@Test

View File

@@ -27,8 +27,8 @@ import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.support.ResourceRegion;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -40,19 +40,22 @@ import static org.mockito.Mockito.mock;
*/
public class HttpRangeTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void invalidFirstPosition() {
HttpRange.createByteRange(-1);
assertThatIllegalArgumentException().isThrownBy(() ->
HttpRange.createByteRange(-1));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void invalidLastLessThanFirst() {
HttpRange.createByteRange(10, 9);
assertThatIllegalArgumentException().isThrownBy(() ->
HttpRange.createByteRange(10, 9));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void invalidSuffixLength() {
HttpRange.createSuffixRange(-1);
assertThatIllegalArgumentException().isThrownBy(() ->
HttpRange.createSuffixRange(-1));
}
@Test
@@ -106,25 +109,20 @@ public class HttpRangeTests {
public void parseRangesValidations() {
// 1. At limit..
StringBuilder sb = new StringBuilder("bytes=0-0");
StringBuilder atLimit = new StringBuilder("bytes=0-0");
for (int i=0; i < 99; i++) {
sb.append(",").append(i).append("-").append(i + 1);
atLimit.append(",").append(i).append("-").append(i + 1);
}
List<HttpRange> ranges = HttpRange.parseRanges(sb.toString());
List<HttpRange> ranges = HttpRange.parseRanges(atLimit.toString());
assertEquals(100, ranges.size());
// 2. Above limit..
sb = new StringBuilder("bytes=0-0");
StringBuilder aboveLimit = new StringBuilder("bytes=0-0");
for (int i=0; i < 100; i++) {
sb.append(",").append(i).append("-").append(i + 1);
}
try {
HttpRange.parseRanges(sb.toString());
fail();
}
catch (IllegalArgumentException ex) {
// Expected
aboveLimit.append(",").append(i).append("-").append(i + 1);
}
assertThatIllegalArgumentException().isThrownBy(() ->
HttpRange.parseRanges(aboveLimit.toString()));
}
@Test
@@ -147,28 +145,31 @@ public class HttpRangeTests {
assertEquals(6L, region.getCount());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void toResourceRegionInputStreamResource() {
InputStreamResource resource = mock(InputStreamResource.class);
HttpRange range = HttpRange.createByteRange(0, 9);
range.toResourceRegion(resource);
assertThatIllegalArgumentException().isThrownBy(() ->
range.toResourceRegion(resource));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void toResourceRegionIllegalLength() {
ByteArrayResource resource = mock(ByteArrayResource.class);
given(resource.contentLength()).willReturn(-1L);
HttpRange range = HttpRange.createByteRange(0, 9);
range.toResourceRegion(resource);
assertThatIllegalArgumentException().isThrownBy(() ->
range.toResourceRegion(resource));
}
@Test(expected = IllegalArgumentException.class)
@Test
@SuppressWarnings("unchecked")
public void toResourceRegionExceptionLength() throws IOException {
InputStreamResource resource = mock(InputStreamResource.class);
given(resource.contentLength()).willThrow(IOException.class);
HttpRange range = HttpRange.createByteRange(0, 9);
range.toResourceRegion(resource);
assertThatIllegalArgumentException().isThrownBy(() ->
range.toResourceRegion(resource));
}
@Test
@@ -177,19 +178,14 @@ public class HttpRangeTests {
ByteArrayResource resource = new ByteArrayResource(bytes);
// 1. Below length
List<HttpRange> ranges = HttpRange.parseRanges("bytes=0-1,2-3");
List<ResourceRegion> regions = HttpRange.toResourceRegions(ranges, resource);
List<HttpRange> belowLengthRanges = HttpRange.parseRanges("bytes=0-1,2-3");
List<ResourceRegion> regions = HttpRange.toResourceRegions(belowLengthRanges, resource);
assertEquals(2, regions.size());
// 2. At length
ranges = HttpRange.parseRanges("bytes=0-1,2-4");
try {
HttpRange.toResourceRegions(ranges, resource);
fail();
}
catch (IllegalArgumentException ex) {
// Expected..
}
List<HttpRange> atLengthRanges = HttpRange.parseRanges("bytes=0-1,2-4");
assertThatIllegalArgumentException().isThrownBy(() ->
HttpRange.toResourceRegions(atLengthRanges, resource));
}
}

View File

@@ -27,6 +27,8 @@ import org.junit.Test;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
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.assertFalse;
import static org.junit.Assert.assertNotNull;
@@ -46,14 +48,16 @@ public class MediaTypeTests {
assertEquals("Invalid toString() returned", "text/plain;q=0.7", result);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void slashInType() {
new MediaType("text/plain");
assertThatIllegalArgumentException().isThrownBy(() ->
new MediaType("text/plain"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void slashInSubtype() {
new MediaType("text", "/");
assertThatIllegalArgumentException().isThrownBy(() ->
new MediaType("text", "/"));
}
@Test
@@ -71,59 +75,70 @@ public class MediaTypeTests {
assertEquals("Invalid quality factor", 0.2D, mediaType.getQualityValue(), 0D);
}
@Test(expected = InvalidMediaTypeException.class)
@Test
public void parseMediaTypeNoSubtype() {
MediaType.parseMediaType("audio");
assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() ->
MediaType.parseMediaType("audio"));
}
@Test(expected = InvalidMediaTypeException.class)
@Test
public void parseMediaTypeNoSubtypeSlash() {
MediaType.parseMediaType("audio/");
assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() ->
MediaType.parseMediaType("audio/"));
}
@Test(expected = InvalidMediaTypeException.class)
@Test
public void parseMediaTypeTypeRange() {
MediaType.parseMediaType("*/json");
assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() ->
MediaType.parseMediaType("*/json"));
}
@Test(expected = InvalidMediaTypeException.class)
@Test
public void parseMediaTypeIllegalType() {
MediaType.parseMediaType("audio(/basic");
assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() ->
MediaType.parseMediaType("audio(/basic"));
}
@Test(expected = InvalidMediaTypeException.class)
@Test
public void parseMediaTypeIllegalSubtype() {
MediaType.parseMediaType("audio/basic)");
assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() ->
MediaType.parseMediaType("audio/basic)"));
}
@Test(expected = InvalidMediaTypeException.class)
@Test
public void parseMediaTypeEmptyParameterAttribute() {
MediaType.parseMediaType("audio/*;=value");
assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() ->
MediaType.parseMediaType("audio/*;=value"));
}
@Test(expected = InvalidMediaTypeException.class)
@Test
public void parseMediaTypeEmptyParameterValue() {
MediaType.parseMediaType("audio/*;attr=");
assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() ->
MediaType.parseMediaType("audio/*;attr="));
}
@Test(expected = InvalidMediaTypeException.class)
@Test
public void parseMediaTypeIllegalParameterAttribute() {
MediaType.parseMediaType("audio/*;attr<=value");
assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() ->
MediaType.parseMediaType("audio/*;attr<=value"));
}
@Test(expected = InvalidMediaTypeException.class)
@Test
public void parseMediaTypeIllegalParameterValue() {
MediaType.parseMediaType("audio/*;attr=v>alue");
assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() ->
MediaType.parseMediaType("audio/*;attr=v>alue"));
}
@Test(expected = InvalidMediaTypeException.class)
@Test
public void parseMediaTypeIllegalQualityFactor() {
MediaType.parseMediaType("audio/basic;q=1.1");
assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() ->
MediaType.parseMediaType("audio/basic;q=1.1"));
}
@Test(expected = InvalidMediaTypeException.class)
@Test
public void parseMediaTypeIllegalCharset() {
MediaType.parseMediaType("text/html; charset=foo-bar");
assertThatExceptionOfType(InvalidMediaTypeException.class).isThrownBy(() ->
MediaType.parseMediaType("text/html; charset=foo-bar"));
}
@Test

View File

@@ -36,9 +36,10 @@ import org.springframework.util.StreamUtils;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@SuppressWarnings("deprecation")
public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMockWebServerTestCase {
@@ -94,12 +95,12 @@ public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMo
assertEquals("Invalid status code", HttpStatus.NOT_FOUND, result.getStatusCode());
}
catch (IOException ex) {
fail(ex.getMessage());
throw new AssertionError(ex.getMessage(), ex);
}
}
@Override
public void onFailure(Throwable ex) {
fail(ex.getMessage());
throw new AssertionError(ex.getMessage(), ex);
}
});
ClientHttpResponse response = listenableFuture.get();
@@ -162,11 +163,8 @@ public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMo
Future<ClientHttpResponse> futureResponse = request.executeAsync();
ClientHttpResponse response = futureResponse.get();
try {
FileCopyUtils.copy(body, request.getBody());
fail("IllegalStateException expected");
}
catch (IllegalStateException ex) {
// expected
assertThatIllegalStateException().isThrownBy(() ->
FileCopyUtils.copy(body, request.getBody()));
}
finally {
response.close();
@@ -183,11 +181,8 @@ public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMo
Future<ClientHttpResponse> futureResponse = request.executeAsync();
ClientHttpResponse response = futureResponse.get();
try {
request.getHeaders().add("MyHeader", "value");
fail("UnsupportedOperationException expected");
}
catch (UnsupportedOperationException ex) {
// expected
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
request.getHeaders().add("MyHeader", "value"));
}
finally {
response.close();

View File

@@ -32,6 +32,8 @@ import org.springframework.http.StreamingHttpOutputMessage;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StreamUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -113,7 +115,7 @@ public abstract class AbstractHttpRequestFactoryTestCase extends AbstractMockWeb
}
}
@Test(expected = IllegalStateException.class)
@Test
public void multipleWrites() throws Exception {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST);
@@ -131,24 +133,22 @@ public abstract class AbstractHttpRequestFactoryTestCase extends AbstractMockWeb
}
request.execute();
FileCopyUtils.copy(body, request.getBody());
assertThatIllegalStateException().isThrownBy(() ->
FileCopyUtils.copy(body, request.getBody()));
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void headersAfterExecute() throws Exception {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/status/ok"), HttpMethod.POST);
request.getHeaders().add("MyHeader", "value");
byte[] body = "Hello World".getBytes("UTF-8");
FileCopyUtils.copy(body, request.getBody());
ClientHttpResponse response = request.execute();
try {
request.getHeaders().add("MyHeader", "value");
}
finally {
response.close();
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> {
FileCopyUtils.copy(body, request.getBody());
try(ClientHttpResponse response = request.execute()) {
request.getHeaders().add("MyHeader", "value");
}
});
}
@Test

View File

@@ -22,6 +22,7 @@ import java.net.Proxy;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
/**
@@ -36,22 +37,25 @@ public class ProxyFactoryBeanTests {
factoryBean = new ProxyFactoryBean();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void noType() {
factoryBean.setType(null);
factoryBean.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(
factoryBean::afterPropertiesSet);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void noHostname() {
factoryBean.setHostname("");
factoryBean.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(
factoryBean::afterPropertiesSet);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void noPort() {
factoryBean.setHostname("example.com");
factoryBean.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(
factoryBean::afterPropertiesSet);
}
@Test

View File

@@ -31,6 +31,7 @@ import org.springframework.http.codec.Pojo;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.util.MimeType;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.springframework.core.ResolvableType.forClass;
@@ -66,16 +67,16 @@ public class Jackson2CborDecoderTests extends AbstractDecoderTestCase<Jackson2Cb
}
@Override
@Test(expected = UnsupportedOperationException.class)
@Test
public void decode() {
Flux<DataBuffer> input = Flux.just(this.pojo1, this.pojo2)
.map(this::writeObject)
.flatMap(this::dataBuffer);
testDecodeAll(input, Pojo.class, step -> step
.expectNext(pojo1)
.expectNext(pojo2)
.verifyComplete());
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
testDecodeAll(input, Pojo.class, step -> step
.expectNext(pojo1)
.expectNext(pojo2)
.verifyComplete()));
}

View File

@@ -33,6 +33,7 @@ import org.springframework.http.codec.ServerSentEvent;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.util.MimeType;
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;
@@ -92,13 +93,14 @@ public class Jackson2CborEncoderTests extends AbstractLeakCheckingTestCase {
pojoConsumer(value).accept(result);
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void encodeStream() {
Pojo pojo1 = new Pojo("foo", "bar");
Pojo pojo2 = new Pojo("foofoo", "barbar");
Pojo pojo3 = new Pojo("foofoofoo", "barbarbar");
Flux<Pojo> input = Flux.just(pojo1, pojo2, pojo3);
ResolvableType type = ResolvableType.forClass(Pojo.class);
encoder.encode(input, this.bufferFactory, type, CBOR_MIME_TYPE, null);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
encoder.encode(input, this.bufferFactory, type, CBOR_MIME_TYPE, null));
}
}

View File

@@ -47,6 +47,7 @@ import org.springframework.util.MimeType;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
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.assertNull;
@@ -94,12 +95,13 @@ public class Jackson2JsonDecoderTests extends AbstractDecoderTestCase<Jackson2Js
assertEquals(Collections.singletonList(textJavascript), decoder.getDecodableMimeTypes());
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void decodableMimeTypesIsImmutable() {
MimeType textJavascript = new MimeType("text", "javascript", StandardCharsets.UTF_8);
Jackson2JsonDecoder decoder = new Jackson2JsonDecoder(new ObjectMapper(), textJavascript);
decoder.getMimeTypes().add(new MimeType("text", "ecmascript"));
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
decoder.getMimeTypes().add(new MimeType("text", "ecmascript")));
}
@Override

View File

@@ -44,6 +44,7 @@ import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import static java.util.Collections.singletonMap;
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;
@@ -100,12 +101,13 @@ public class Jackson2JsonEncoderTests extends AbstractEncoderTestCase<Jackson2Js
assertEquals(Collections.singletonList(textJavascript), encoder.getEncodableMimeTypes());
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void encodableMimeTypesIsImmutable() {
MimeType textJavascript = new MimeType("text", "javascript", StandardCharsets.UTF_8);
Jackson2JsonEncoder encoder = new Jackson2JsonEncoder(new ObjectMapper(), textJavascript);
encoder.getMimeTypes().add(new MimeType("text", "ecmascript"));
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
encoder.getMimeTypes().add(new MimeType("text", "ecmascript")));
}
@Test

View File

@@ -37,7 +37,6 @@ import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.core.ResolvableType.forClass;
/**
@@ -148,7 +147,9 @@ public class DefaultMultipartMessageReaderTests extends AbstractDataBufferAlloca
CountDownLatch latch = new CountDownLatch(1);
file.transferTo(tempFile)
.subscribe(null,
throwable -> fail(throwable.getMessage()),
throwable -> {
throw new AssertionError(throwable.getMessage(), throwable);
},
() -> {
try {
verifyContents(tempFile, contents);

View File

@@ -36,6 +36,7 @@ import org.springframework.protobuf.SecondMsg;
import org.springframework.util.MimeType;
import static java.util.Collections.emptyMap;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.springframework.core.ResolvableType.forClass;
@@ -63,9 +64,10 @@ public class ProtobufDecoderTests extends AbstractDecoderTestCase<ProtobufDecode
}
@Test(expected = IllegalArgumentException.class)
@Test
public void extensionRegistryNull() {
new ProtobufDecoder(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new ProtobufDecoder(null));
}
@Override

View File

@@ -26,7 +26,6 @@ import org.springframework.http.MediaType;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Test-case for AbstractHttpMessageConverter.
@@ -92,14 +91,13 @@ public class HttpMessageConverterTests {
@Override
protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
fail("Not expected");
return null;
throw new AssertionError("Not expected");
}
@Override
protected void writeInternal(T t, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
fail("Not expected");
throw new AssertionError("Not expected");
}
}

View File

@@ -34,6 +34,7 @@ import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -171,9 +172,10 @@ public class ObjectToStringHttpMessageConverterTests {
assertArrayEquals(new byte[] { -2, -1, 0, '9', 0, '5', 0, '8' }, this.servletResponse.getContentAsByteArray());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testConversionServiceRequired() {
new ObjectToStringHttpMessageConverter(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new ObjectToStringHttpMessageConverter(null));
}
}

View File

@@ -35,6 +35,7 @@ import org.springframework.http.MockHttpInputMessage;
import org.springframework.http.MockHttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -166,12 +167,13 @@ public class GsonHttpMessageConverterTests {
assertEquals("Invalid content-type", contentType, outputMessage.getHeaders().getContentType());
}
@Test(expected = HttpMessageNotReadableException.class)
@Test
public void readInvalidJson() throws IOException {
String body = "FooBar";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
this.converter.read(MyBean.class, inputMessage);
assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() ->
this.converter.read(MyBean.class, inputMessage));
}
@Test

View File

@@ -83,6 +83,8 @@ import org.junit.Test;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
@@ -107,9 +109,10 @@ public class Jackson2ObjectMapperBuilderTests {
private static final String DATA = "{\"offsetDateTime\": \"2020-01-01T00:00:00\"}";
@Test(expected = FatalBeanException.class)
@Test
public void unknownFeature() {
Jackson2ObjectMapperBuilder.json().featuresToEnable(Boolean.TRUE).build();
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() ->
Jackson2ObjectMapperBuilder.json().featuresToEnable(Boolean.TRUE).build());
}
@Test
@@ -226,10 +229,11 @@ public class Jackson2ObjectMapperBuilderTests {
assertEquals(timeZone, objectMapper.getDeserializationConfig().getTimeZone());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void wrongTimeZoneStringSetter() {
String zoneId = "foo";
Jackson2ObjectMapperBuilder.json().timeZone(zoneId).build();
assertThatIllegalArgumentException().isThrownBy(() ->
Jackson2ObjectMapperBuilder.json().timeZone(zoneId).build());
}
@Test

View File

@@ -64,6 +64,7 @@ import org.junit.Test;
import org.springframework.beans.FatalBeanException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
@@ -91,10 +92,11 @@ public class Jackson2ObjectMapperFactoryBeanTests {
private final Jackson2ObjectMapperFactoryBean factory = new Jackson2ObjectMapperFactoryBean();
@Test(expected = FatalBeanException.class)
@Test
public void unknownFeature() {
this.factory.setFeaturesToEnable(Boolean.TRUE);
this.factory.afterPropertiesSet();
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(
this.factory::afterPropertiesSet);
}
@Test

View File

@@ -35,6 +35,7 @@ import org.springframework.http.MockHttpInputMessage;
import org.springframework.http.MockHttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -166,12 +167,13 @@ public class JsonbHttpMessageConverterTests {
assertEquals("Invalid content-type", contentType, outputMessage.getHeaders().getContentType());
}
@Test(expected = HttpMessageNotReadableException.class)
@Test
public void readInvalidJson() throws IOException {
String body = "FooBar";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
this.converter.read(MyBean.class, inputMessage);
assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() ->
this.converter.read(MyBean.class, inputMessage));
}
@Test

View File

@@ -42,13 +42,13 @@ import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.lang.Nullable;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Jackson 2.x converter tests.
@@ -180,12 +180,13 @@ public class MappingJackson2HttpMessageConverterTests {
assertEquals("Invalid content-type", contentType, outputMessage.getHeaders().getContentType());
}
@Test(expected = HttpMessageNotReadableException.class)
@Test
public void readInvalidJson() throws IOException {
String body = "FooBar";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
converter.read(MyBean.class, inputMessage);
assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() ->
converter.read(MyBean.class, inputMessage));
}
@Test
@@ -442,14 +443,9 @@ public class MappingJackson2HttpMessageConverterTests {
String body = "{\"property1\":\"foo\",\"property2\":\"bar\"}";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
try {
converter.read(BeanWithNoDefaultConstructor.class, inputMessage);
}
catch (HttpMessageConversionException ex) {
assertTrue(ex.getMessage(), ex.getMessage().startsWith("Type definition error:"));
return;
}
fail();
assertThatExceptionOfType(HttpMessageConversionException.class).isThrownBy(() ->
converter.read(BeanWithNoDefaultConstructor.class, inputMessage))
.withMessageStartingWith("Type definition error:");
}

View File

@@ -32,10 +32,10 @@ import org.springframework.oxm.MarshallingFailureException;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.UnmarshallingFailureException;
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;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.BDDMockito.given;
@@ -104,13 +104,9 @@ public class MarshallingHttpMessageConverterTests {
given(unmarshaller.unmarshal(isA(StreamSource.class))).willReturn(Integer.valueOf(3));
MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller, unmarshaller);
try {
converter.read(String.class, inputMessage);
fail("Should have thrown HttpMessageNotReadableException");
}
catch (HttpMessageNotReadableException ex) {
assertTrue(ex.getCause() instanceof TypeMismatchException);
}
assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() ->
converter.read(String.class, inputMessage))
.withCauseInstanceOf(TypeMismatchException.class);
}
@Test
@@ -124,13 +120,9 @@ public class MarshallingHttpMessageConverterTests {
MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter();
converter.setUnmarshaller(unmarshaller);
try {
converter.read(Object.class, inputMessage);
fail("HttpMessageNotReadableException should be thrown");
}
catch (HttpMessageNotReadableException e) {
assertTrue("Invalid exception hierarchy", e.getCause() == ex);
}
assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() ->
converter.read(Object.class, inputMessage))
.withCause(ex);
}
@Test
@@ -157,18 +149,15 @@ public class MarshallingHttpMessageConverterTests {
Marshaller marshaller = mock(Marshaller.class);
willThrow(ex).given(marshaller).marshal(eq(body), isA(Result.class));
try {
MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller);
converter.write(body, null, outputMessage);
fail("HttpMessageNotWritableException should be thrown");
}
catch (HttpMessageNotWritableException e) {
assertTrue("Invalid exception hierarchy", e.getCause() == ex);
}
MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller);
assertThatExceptionOfType(HttpMessageNotWritableException.class).isThrownBy(() ->
converter.write(body, null, outputMessage))
.withCause(ex);
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void supports() throws Exception {
new MarshallingHttpMessageConverter().supports(Object.class);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
new MarshallingHttpMessageConverter().supports(Object.class));
}
}

View File

@@ -30,10 +30,10 @@ import org.springframework.http.HttpStatus;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
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.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for {@link ContextPathCompositeHandler}.
@@ -50,13 +50,9 @@ public class ContextPathCompositeHandlerTests {
}
private void testInvalid(String contextPath, String expectedError) {
try {
new ContextPathCompositeHandler(Collections.singletonMap(contextPath, new TestHttpHandler()));
fail();
}
catch (IllegalArgumentException ex) {
assertEquals(expectedError, ex.getMessage());
}
assertThatIllegalArgumentException().isThrownBy(() ->
new ContextPathCompositeHandler(Collections.singletonMap(contextPath, new TestHttpHandler())))
.withMessage(expectedError);
}
@Test

View File

@@ -34,6 +34,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
@@ -110,9 +111,10 @@ public class ServerHttpRequestTests {
assertEquals("/app", request.getPath().contextPath().value());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void mutateWithInvalidPath() throws Exception {
createHttpRequest("/").mutate().path("foo-bar");
assertThatIllegalArgumentException().isThrownBy(() ->
createHttpRequest("/").mutate().path("foo-bar"));
}
@Test // SPR-16434

View File

@@ -46,11 +46,12 @@ import org.springframework.remoting.support.RemoteInvocationResult;
import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@@ -118,20 +119,10 @@ public class HttpInvokerTests {
assertTrue(Arrays.equals(new int[] {1, 2, 3}, intArray[0]));
assertTrue(Arrays.equals(new int[] {4, 5, 6}, intArray[1]));
try {
proxy.exceptional(new IllegalStateException());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
try {
proxy.exceptional(new IllegalAccessException());
fail("Should have thrown IllegalAccessException");
}
catch (IllegalAccessException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
proxy.exceptional(new IllegalStateException()));
assertThatExceptionOfType(IllegalAccessException.class).isThrownBy(() ->
proxy.exceptional(new IllegalAccessException()));
}
@Test
@@ -157,14 +148,9 @@ public class HttpInvokerTests {
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
try {
proxy.setAge(50);
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
assertTrue(ex.getCause() instanceof IOException);
}
assertThatExceptionOfType(RemoteAccessException.class).isThrownBy(() ->
proxy.setAge(50))
.withCauseInstanceOf(IOException.class);
}
@Test
@@ -236,20 +222,10 @@ public class HttpInvokerTests {
proxy.setAge(50);
assertEquals(50, proxy.getAge());
try {
proxy.exceptional(new IllegalStateException());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
try {
proxy.exceptional(new IllegalAccessException());
fail("Should have thrown IllegalAccessException");
}
catch (IllegalAccessException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
proxy.exceptional(new IllegalStateException()));
assertThatExceptionOfType(IllegalAccessException.class).isThrownBy(() ->
proxy.exceptional(new IllegalAccessException()));
}
@Test
@@ -316,20 +292,10 @@ public class HttpInvokerTests {
proxy.setAge(50);
assertEquals(50, proxy.getAge());
try {
proxy.exceptional(new IllegalStateException());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
try {
proxy.exceptional(new IllegalAccessException());
fail("Should have thrown IllegalAccessException");
}
catch (IllegalAccessException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
proxy.exceptional(new IllegalStateException()));
assertThatExceptionOfType(IllegalAccessException.class).isThrownBy(() ->
proxy.exceptional(new IllegalAccessException()));
}
@Test
@@ -360,13 +326,8 @@ public class HttpInvokerTests {
public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) {
RemoteInvocation invocation = new RemoteInvocation(methodInvocation);
invocation.addAttribute("myKey", "myValue");
try {
invocation.addAttribute("myKey", "myValue");
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected: already defined
}
assertThatIllegalStateException().isThrownBy(() ->
invocation.addAttribute("myKey", "myValue"));
assertNotNull(invocation.getAttributes());
assertEquals(1, invocation.getAttributes().size());
assertEquals("myValue", invocation.getAttributes().get("myKey"));
@@ -472,14 +433,10 @@ public class HttpInvokerTests {
assertTrue(proxy.equals(proxy));
// should go through
try {
proxy.setAge(50);
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
assertTrue(ex.getCause() instanceof IOException);
}
assertThatExceptionOfType(RemoteAccessException.class).isThrownBy(() ->
proxy.setAge(50))
.withCauseInstanceOf(IOException.class);
}

View File

@@ -36,9 +36,9 @@ import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.remoting.RemoteAccessException;
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;
/**
* @author Juergen Hoeller
@@ -101,30 +101,20 @@ public class JaxWsSupportTests {
String order = orderService.getOrder(1000);
assertEquals("order 1000", order);
try {
orderService.getOrder(0);
fail("Should have thrown OrderNotFoundException");
}
catch (OrderNotFoundException ex) {
// expected
}
catch (RemoteAccessException ex) {
// ignore - probably setup issue with JAX-WS provider vs JAXB
}
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
orderService.getOrder(0))
.matches(ex -> ex instanceof OrderNotFoundException ||
ex instanceof RemoteAccessException);
// ignore RemoteAccessException as probably setup issue with JAX-WS provider vs JAXB
ServiceAccessor serviceAccessor = ac.getBean("accessor", ServiceAccessor.class);
order = serviceAccessor.orderService.getOrder(1000);
assertEquals("order 1000", order);
try {
serviceAccessor.orderService.getOrder(0);
fail("Should have thrown OrderNotFoundException");
}
catch (OrderNotFoundException ex) {
// expected
}
catch (WebServiceException ex) {
// ignore - probably setup issue with JAX-WS provider vs JAXB
}
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
serviceAccessor.orderService.getOrder(0))
.matches(ex -> ex instanceof OrderNotFoundException ||
ex instanceof WebServiceException);
// ignore WebServiceException as probably setup issue with JAX-WS provider vs JAXB
}
catch (BeanCreationException ex) {
if ("exporter".equals(ex.getBeanName()) && ex.getRootCause() instanceof ClassNotFoundException) {

View File

@@ -33,6 +33,7 @@ import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
/**
@@ -128,7 +129,7 @@ public class ContentNegotiationManagerFactoryBeanTests {
assertEquals(Collections.singletonList(MediaType.IMAGE_GIF), manager.resolveMediaTypes(this.webRequest));
}
@Test(expected = HttpMediaTypeNotAcceptableException.class) // SPR-10170
@Test // SPR-10170
public void favorPathWithIgnoreUnknownPathExtensionTurnedOff() throws Exception {
this.factoryBean.setFavorPathExtension(true);
this.factoryBean.setIgnoreUnknownPathExtensions(false);
@@ -138,7 +139,8 @@ public class ContentNegotiationManagerFactoryBeanTests {
this.servletRequest.setRequestURI("/flower.foobarbaz");
this.servletRequest.addParameter("format", "json");
manager.resolveMediaTypes(this.webRequest);
assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() ->
manager.resolveMediaTypes(this.webRequest));
}
@Test
@@ -159,7 +161,7 @@ public class ContentNegotiationManagerFactoryBeanTests {
manager.resolveMediaTypes(this.webRequest));
}
@Test(expected = HttpMediaTypeNotAcceptableException.class) // SPR-10170
@Test // SPR-10170
public void favorParameterWithUnknownMediaType() throws HttpMediaTypeNotAcceptableException {
this.factoryBean.setFavorParameter(true);
this.factoryBean.afterPropertiesSet();
@@ -168,7 +170,8 @@ public class ContentNegotiationManagerFactoryBeanTests {
this.servletRequest.setRequestURI("/flower");
this.servletRequest.setParameter("format", "invalid");
manager.resolveMediaTypes(this.webRequest);
assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() ->
manager.resolveMediaTypes(this.webRequest));
}
@Test

View File

@@ -26,6 +26,7 @@ import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
/**
@@ -68,10 +69,11 @@ public class HeaderContentNegotiationStrategyTests {
assertEquals("text/plain;q=0.5", mediaTypes.get(3).toString());
}
@Test(expected = HttpMediaTypeNotAcceptableException.class)
@Test
public void resolveMediaTypesParseError() throws Exception {
this.servletRequest.addHeader("Accept", "textplain; q=0.5");
this.strategy.resolveMediaTypes(this.webRequest);
assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() ->
this.strategy.resolveMediaTypes(this.webRequest));
}
}

View File

@@ -29,6 +29,7 @@ import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
/**
@@ -122,14 +123,15 @@ public class PathExtensionContentNegotiationStrategyTests {
assertEquals(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, mediaTypes);
}
@Test(expected = HttpMediaTypeNotAcceptableException.class)
@Test
public void resolveMediaTypesDoNotIgnoreUnknownExtension() throws Exception {
this.servletRequest.setRequestURI("test.foobar");
PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy();
strategy.setIgnoreUnknownExtensions(false);
strategy.resolveMediaTypes(this.webRequest);
assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() ->
strategy.resolveMediaTypes(this.webRequest));
}
}

View File

@@ -23,11 +23,11 @@ import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup;
import org.springframework.util.StopWatch;
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.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@@ -48,31 +48,16 @@ public class ServletRequestUtilsTests {
assertEquals(ServletRequestUtils.getRequiredIntParameter(request, "param1"), 5);
assertEquals(ServletRequestUtils.getIntParameter(request, "param2", 6), 6);
try {
ServletRequestUtils.getRequiredIntParameter(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredIntParameter(request, "param2"));
assertEquals(ServletRequestUtils.getIntParameter(request, "param3"), null);
assertEquals(ServletRequestUtils.getIntParameter(request, "param3", 6), 6);
try {
ServletRequestUtils.getRequiredIntParameter(request, "param3");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredIntParameter(request, "param3"));
try {
ServletRequestUtils.getRequiredIntParameter(request, "paramEmpty");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredIntParameter(request, "paramEmpty"));
}
@Test
@@ -91,13 +76,8 @@ public class ServletRequestUtilsTests {
assertEquals(array[i], values[i]);
}
try {
ServletRequestUtils.getRequiredIntParameters(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredIntParameters(request, "param2"));
}
@Test
@@ -112,31 +92,16 @@ public class ServletRequestUtilsTests {
assertEquals(ServletRequestUtils.getRequiredIntParameter(request, "param1"), 5L);
assertEquals(ServletRequestUtils.getLongParameter(request, "param2", 6L), 6L);
try {
ServletRequestUtils.getRequiredLongParameter(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredLongParameter(request, "param2"));
assertEquals(ServletRequestUtils.getLongParameter(request, "param3"), null);
assertEquals(ServletRequestUtils.getLongParameter(request, "param3", 6L), 6L);
try {
ServletRequestUtils.getRequiredLongParameter(request, "param3");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredLongParameter(request, "param3"));
try {
ServletRequestUtils.getRequiredLongParameter(request, "paramEmpty");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredLongParameter(request, "paramEmpty"));
}
@Test
@@ -156,13 +121,8 @@ public class ServletRequestUtilsTests {
assertEquals(array[i], values[i]);
}
try {
ServletRequestUtils.getRequiredLongParameters(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredLongParameters(request, "param2"));
request.setParameter("param2", new String[] {"1", "2"});
values = ServletRequestUtils.getRequiredLongParameters(request, "param2");
@@ -171,13 +131,8 @@ public class ServletRequestUtilsTests {
assertEquals(2, values[1]);
request.removeParameter("param2");
try {
ServletRequestUtils.getRequiredLongParameters(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredLongParameters(request, "param2"));
}
@Test
@@ -192,31 +147,16 @@ public class ServletRequestUtilsTests {
assertTrue(ServletRequestUtils.getRequiredFloatParameter(request, "param1") == 5.5f);
assertTrue(ServletRequestUtils.getFloatParameter(request, "param2", 6.5f) == 6.5f);
try {
ServletRequestUtils.getRequiredFloatParameter(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredFloatParameter(request, "param2"));
assertTrue(ServletRequestUtils.getFloatParameter(request, "param3") == null);
assertTrue(ServletRequestUtils.getFloatParameter(request, "param3", 6.5f) == 6.5f);
try {
ServletRequestUtils.getRequiredFloatParameter(request, "param3");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredFloatParameter(request, "param3"));
try {
ServletRequestUtils.getRequiredFloatParameter(request, "paramEmpty");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredFloatParameter(request, "paramEmpty"));
}
@Test
@@ -235,13 +175,8 @@ public class ServletRequestUtilsTests {
assertEquals(array[i], values[i], 0);
}
try {
ServletRequestUtils.getRequiredFloatParameters(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredFloatParameters(request, "param2"));
}
@Test
@@ -256,31 +191,16 @@ public class ServletRequestUtilsTests {
assertTrue(ServletRequestUtils.getRequiredDoubleParameter(request, "param1") == 5.5);
assertTrue(ServletRequestUtils.getDoubleParameter(request, "param2", 6.5) == 6.5);
try {
ServletRequestUtils.getRequiredDoubleParameter(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredDoubleParameter(request, "param2"));
assertTrue(ServletRequestUtils.getDoubleParameter(request, "param3") == null);
assertTrue(ServletRequestUtils.getDoubleParameter(request, "param3", 6.5) == 6.5);
try {
ServletRequestUtils.getRequiredDoubleParameter(request, "param3");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredDoubleParameter(request, "param3"));
try {
ServletRequestUtils.getRequiredDoubleParameter(request, "paramEmpty");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredDoubleParameter(request, "paramEmpty"));
}
@Test
@@ -299,13 +219,8 @@ public class ServletRequestUtilsTests {
assertEquals(array[i], values[i], 0);
}
try {
ServletRequestUtils.getRequiredDoubleParameters(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredDoubleParameters(request, "param2"));
}
@Test
@@ -326,13 +241,8 @@ public class ServletRequestUtilsTests {
assertTrue(ServletRequestUtils.getBooleanParameter(request, "param3") == null);
assertTrue(ServletRequestUtils.getBooleanParameter(request, "param3", true));
try {
ServletRequestUtils.getRequiredBooleanParameter(request, "param3");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredBooleanParameter(request, "param3"));
assertTrue(ServletRequestUtils.getBooleanParameter(request, "param4", false));
assertTrue(ServletRequestUtils.getRequiredBooleanParameter(request, "param4"));
@@ -379,13 +289,8 @@ public class ServletRequestUtilsTests {
assertEquals(null, ServletRequestUtils.getStringParameter(request, "param3"));
assertEquals("string", ServletRequestUtils.getStringParameter(request, "param3", "string"));
assertNull(ServletRequestUtils.getStringParameter(request, "param3", null));
try {
ServletRequestUtils.getRequiredStringParameter(request, "param3");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
ServletRequestUtils.getRequiredStringParameter(request, "param3"));
assertEquals("", ServletRequestUtils.getStringParameter(request, "paramEmpty"));
assertEquals("", ServletRequestUtils.getRequiredStringParameter(request, "paramEmpty"));

View File

@@ -44,6 +44,7 @@ import org.springframework.util.MultiValueMap;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -351,19 +352,17 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest
@Test
public void notFoundGet() throws Exception {
try {
Future<?> future = template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null);
future.get();
fail("HttpClientErrorException expected");
}
catch (ExecutionException ex) {
assertTrue(ex.getCause() instanceof HttpClientErrorException);
HttpClientErrorException cause = (HttpClientErrorException)ex.getCause();
assertEquals(HttpStatus.NOT_FOUND, cause.getStatusCode());
assertNotNull(cause.getStatusText());
assertNotNull(cause.getResponseBodyAsString());
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> {
Future<?> future = template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null);
future.get();
})
.withCauseInstanceOf(HttpClientErrorException.class)
.satisfies(ex -> {
HttpClientErrorException cause = (HttpClientErrorException) ex.getCause();
assertEquals(HttpStatus.NOT_FOUND, cause.getStatusCode());
assertNotNull(cause.getStatusText());
assertNotNull(cause.getResponseBodyAsString());
});
}
@Test

View File

@@ -26,9 +26,8 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.http.HttpStatus.BAD_GATEWAY;
@@ -104,14 +103,8 @@ public class DefaultResponseErrorHandlerHttpStatusTests {
given(this.response.getRawStatusCode()).willReturn(this.httpStatus.value());
given(this.response.getHeaders()).willReturn(headers);
try {
this.handler.handleError(this.response);
fail("expected " + this.expectedExceptionClass.getSimpleName());
}
catch (HttpStatusCodeException ex) {
assertEquals("Expected " + this.expectedExceptionClass.getSimpleName(),
this.expectedExceptionClass, ex.getClass());
}
assertThatExceptionOfType(expectedExceptionClass).isThrownBy(() ->
this.handler.handleError(this.response));
}
}

View File

@@ -28,11 +28,11 @@ import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;
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.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -72,16 +72,12 @@ public class DefaultResponseErrorHandlerTests {
given(response.getHeaders()).willReturn(headers);
given(response.getBody()).willReturn(new ByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8)));
try {
handler.handleError(response);
fail("expected HttpClientErrorException");
}
catch (HttpClientErrorException ex) {
assertSame(headers, ex.getResponseHeaders());
}
assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() ->
handler.handleError(response))
.satisfies(ex -> assertThat(ex.getResponseHeaders()).isSameAs(headers));
}
@Test(expected = HttpClientErrorException.class)
@Test
public void handleErrorIOException() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
@@ -91,10 +87,11 @@ public class DefaultResponseErrorHandlerTests {
given(response.getHeaders()).willReturn(headers);
given(response.getBody()).willThrow(new IOException());
handler.handleError(response);
assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() ->
handler.handleError(response));
}
@Test(expected = HttpClientErrorException.class)
@Test
public void handleErrorNullResponse() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
@@ -103,7 +100,8 @@ public class DefaultResponseErrorHandlerTests {
given(response.getStatusText()).willReturn("Not Found");
given(response.getHeaders()).willReturn(headers);
handler.handleError(response);
assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() ->
handler.handleError(response));
}
@Test // SPR-16108
@@ -118,7 +116,7 @@ public class DefaultResponseErrorHandlerTests {
assertFalse(handler.hasError(response));
}
@Test(expected = UnknownHttpStatusCodeException.class) // SPR-9406
@Test // SPR-9406
public void handleErrorUnknownStatusCode() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
@@ -127,7 +125,8 @@ public class DefaultResponseErrorHandlerTests {
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
handler.handleError(response);
assertThatExceptionOfType(UnknownHttpStatusCodeException.class).isThrownBy(() ->
handler.handleError(response));
}
@Test // SPR-17461
@@ -142,7 +141,7 @@ public class DefaultResponseErrorHandlerTests {
assertTrue(handler.hasError(response));
}
@Test(expected = UnknownHttpStatusCodeException.class)
@Test
public void handleErrorForCustomClientError() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
@@ -151,7 +150,8 @@ public class DefaultResponseErrorHandlerTests {
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
handler.handleError(response);
assertThatExceptionOfType(UnknownHttpStatusCodeException.class).isThrownBy(() ->
handler.handleError(response));
}
@Test // SPR-17461
@@ -166,7 +166,7 @@ public class DefaultResponseErrorHandlerTests {
assertTrue(handler.hasError(response));
}
@Test(expected = UnknownHttpStatusCodeException.class)
@Test
public void handleErrorForCustomServerError() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
@@ -175,7 +175,8 @@ public class DefaultResponseErrorHandlerTests {
given(response.getStatusText()).willReturn("Custom status code");
given(response.getHeaders()).willReturn(headers);
handler.handleError(response);
assertThatExceptionOfType(UnknownHttpStatusCodeException.class).isThrownBy(() ->
handler.handleError(response));
}
@Test // SPR-16604

View File

@@ -30,11 +30,12 @@ import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -99,13 +100,9 @@ public class ExtractingResponseErrorHandlerTests {
responseHeaders.setContentLength(body.length);
given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));
try {
this.errorHandler.handleError(this.response);
fail("MyRestClientException expected");
}
catch (MyRestClientException ex) {
assertEquals("bar", ex.getFoo());
}
assertThatExceptionOfType(MyRestClientException.class).isThrownBy(() ->
this.errorHandler.handleError(this.response))
.satisfies(ex -> assertThat(ex.getFoo()).isEqualTo("bar"));
}
@Test
@@ -119,13 +116,9 @@ public class ExtractingResponseErrorHandlerTests {
responseHeaders.setContentLength(body.length);
given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));
try {
this.errorHandler.handleError(this.response);
fail("MyRestClientException expected");
}
catch (MyRestClientException ex) {
assertEquals("bar", ex.getFoo());
}
assertThatExceptionOfType(MyRestClientException.class).isThrownBy(() ->
this.errorHandler.handleError(this.response))
.satisfies(ex -> assertThat(ex.getFoo()).isEqualTo("bar"));
}
@Test
@@ -139,14 +132,12 @@ public class ExtractingResponseErrorHandlerTests {
responseHeaders.setContentLength(body.length);
given(this.response.getBody()).willReturn(new ByteArrayInputStream(body));
try {
this.errorHandler.handleError(this.response);
fail("HttpClientErrorException expected");
}
catch (HttpClientErrorException ex) {
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
assertArrayEquals(body, ex.getResponseBodyAsByteArray());
}
assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() ->
this.errorHandler.handleError(this.response))
.satisfies(ex -> {
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
assertArrayEquals(body, ex.getResponseBodyAsByteArray());
});
}
@Test

View File

@@ -54,13 +54,13 @@ import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeFalse;
import static org.springframework.http.HttpMethod.POST;
@@ -173,40 +173,34 @@ public class RestTemplateIntegrationTests extends AbstractMockWebServerTestCase
@Test
public void notFound() {
try {
template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null);
fail("HttpClientErrorException expected");
}
catch (HttpClientErrorException ex) {
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
assertNotNull(ex.getStatusText());
assertNotNull(ex.getResponseBodyAsString());
}
assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() ->
template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null))
.satisfies(ex -> {
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
assertNotNull(ex.getStatusText());
assertNotNull(ex.getResponseBodyAsString());
});
}
@Test
public void badRequest() {
try {
template.execute(baseUrl + "/status/badrequest", HttpMethod.GET, null, null);
fail("HttpClientErrorException.BadRequest expected");
}
catch (HttpClientErrorException.BadRequest ex) {
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
assertEquals("400 Client Error", ex.getMessage());
}
assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() ->
template.execute(baseUrl + "/status/badrequest", HttpMethod.GET, null, null))
.satisfies(ex -> {
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
assertEquals("400 Client Error", ex.getMessage());
});
}
@Test
public void serverError() {
try {
template.execute(baseUrl + "/status/server", HttpMethod.GET, null, null);
fail("HttpServerErrorException expected");
}
catch (HttpServerErrorException ex) {
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, ex.getStatusCode());
assertNotNull(ex.getStatusText());
assertNotNull(ex.getResponseBodyAsString());
}
assertThatExceptionOfType(HttpServerErrorException.class).isThrownBy(() ->
template.execute(baseUrl + "/status/server", HttpMethod.GET, null, null))
.satisfies(ex -> {
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, ex.getStatusCode());
assertNotNull(ex.getStatusText());
assertNotNull(ex.getResponseBodyAsString());
});
}
@Test

View File

@@ -47,13 +47,13 @@ import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StreamUtils;
import org.springframework.web.util.DefaultUriBuilderFactory;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@@ -168,13 +168,8 @@ public class RestTemplateTests {
willThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR))
.given(errorHandler).handleError(new URI(url), GET, response);
try {
template.execute(url, GET, null, null);
fail("HttpServerErrorException expected");
}
catch (HttpServerErrorException ex) {
// expected
}
assertThatExceptionOfType(HttpServerErrorException.class).isThrownBy(() ->
template.execute(url, GET, null, null));
verify(response).close();
}
@@ -209,13 +204,8 @@ public class RestTemplateTests {
mockResponseBody("Foo", new MediaType("bar", "baz"));
given(converter.canRead(String.class, barBaz)).willReturn(false);
try {
template.getForObject("https://example.com/{p}", String.class, "resource");
fail("UnsupportedMediaTypeException expected");
}
catch (RestClientException ex) {
// expected
}
assertThatExceptionOfType(RestClientException.class).isThrownBy(() ->
template.getForObject("https://example.com/{p}", String.class, "resource"));
verify(response).close();
}
@@ -547,15 +537,10 @@ public class RestTemplateTests {
mockHttpMessageConverter(new MediaType("foo", "bar"), String.class);
given(request.execute()).willThrow(new IOException("Socket failure"));
try {
template.getForObject(url, String.class);
fail("RestClientException expected");
}
catch (ResourceAccessException ex) {
assertEquals("I/O error on GET request for \"https://example.com/resource\": " +
"Socket failure; nested exception is java.io.IOException: Socket failure",
ex.getMessage());
}
assertThatExceptionOfType(ResourceAccessException.class).isThrownBy(() ->
template.getForObject(url, String.class))
.withMessage("I/O error on GET request for \"https://example.com/resource\": " +
"Socket failure; nested exception is java.io.IOException: Socket failure");
}
@Test // SPR-15900
@@ -570,15 +555,10 @@ public class RestTemplateTests {
given(request.getHeaders()).willReturn(new HttpHeaders());
given(request.execute()).willThrow(new IOException("Socket failure"));
try {
template.getForObject(uri, String.class);
fail("RestClientException expected");
}
catch (ResourceAccessException ex) {
assertEquals("I/O error on GET request for \"https://example.com/resource\": " +
"Socket failure; nested exception is java.io.IOException: Socket failure",
ex.getMessage());
}
assertThatExceptionOfType(ResourceAccessException.class).isThrownBy(() ->
template.getForObject(uri, String.class))
.withMessage("I/O error on GET request for \"https://example.com/resource\": " +
"Socket failure; nested exception is java.io.IOException: Socket failure");
}
@Test

View File

@@ -27,10 +27,10 @@ import org.springframework.tests.sample.beans.TestBean;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.StaticWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
/**
* @author Rod Johnson
@@ -69,13 +69,8 @@ public class RequestAndSessionScopedBeanTests {
assertNotSame(target3, target);
RequestContextHolder.setRequestAttributes(null);
try {
wac.getBean(targetBeanName);
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
// expected
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
wac.getBean(targetBeanName));
}
@Test
@@ -97,15 +92,8 @@ public class RequestAndSessionScopedBeanTests {
assertSame(target, request.getSession().getAttribute(targetBeanName));
RequestContextHolder.setRequestAttributes(null);
try {
wac.getBean(targetBeanName);
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
// expected
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
wac.getBean(targetBeanName));
}
}

View File

@@ -31,6 +31,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.tests.sample.beans.DerivedTestBean;
import org.springframework.tests.sample.beans.TestBean;
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.assertNotNull;
@@ -38,7 +39,6 @@ import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@@ -117,16 +117,11 @@ public class RequestScopeTests {
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
String name = "requestScopedObjectCircle1";
assertNull(request.getAttribute(name));
this.beanFactory.getBean(name);
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
}
String name = "requestScopedObjectCircle1";
assertNull(request.getAttribute(name));
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
this.beanFactory.getBean(name))
.matches(ex -> ex.contains(BeanCurrentlyInCreationException.class));
}
@Test

View File

@@ -26,9 +26,10 @@ import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpSession;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -49,9 +50,10 @@ public class ServletRequestAttributesTests {
};
@Test(expected = IllegalArgumentException.class)
@Test
public void ctorRejectsNullArg() throws Exception {
new ServletRequestAttributes(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new ServletRequestAttributes(null));
}
@Test
@@ -68,13 +70,8 @@ public class ServletRequestAttributesTests {
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
request.close();
try {
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_REQUEST);
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_REQUEST));
}
@Test

View File

@@ -26,14 +26,12 @@ import org.springframework.mock.web.test.MockAsyncContext;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
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.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -93,25 +91,17 @@ public class StandardServletAsyncWebRequestTests {
@Test
public void startAsyncNotSupported() throws Exception {
this.request.setAsyncSupported(false);
try {
this.asyncRequest.startAsync();
fail("expected exception");
}
catch (IllegalStateException ex) {
assertThat(ex.getMessage(), containsString("Async support must be enabled"));
}
assertThatIllegalStateException().isThrownBy(
this.asyncRequest::startAsync)
.withMessageContaining("Async support must be enabled");
}
@Test
public void startAsyncAfterCompleted() throws Exception {
this.asyncRequest.onComplete(new AsyncEvent(new MockAsyncContext(this.request, this.response)));
try {
this.asyncRequest.startAsync();
fail("expected exception");
}
catch (IllegalStateException ex) {
assertEquals("Async processing has already completed", ex.getMessage());
}
assertThatIllegalStateException().isThrownBy(
this.asyncRequest::startAsync)
.withMessage("Async processing has already completed");
}
@Test
@@ -138,10 +128,11 @@ public class StandardServletAsyncWebRequestTests {
verify(errorHandler).accept(e);
}
@Test(expected = IllegalStateException.class)
@Test
public void setTimeoutDuringConcurrentHandling() {
this.asyncRequest.startAsync();
this.asyncRequest.setTimeout(25L);
assertThatIllegalStateException().isThrownBy(() ->
this.asyncRequest.setTimeout(25L));
}
@Test

View File

@@ -27,10 +27,12 @@ import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.mock.web.test.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
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.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.notNull;
import static org.mockito.BDDMockito.given;
@@ -69,21 +71,13 @@ public class WebAsyncManagerTests {
public void startAsyncProcessingWithoutAsyncWebRequest() throws Exception {
WebAsyncManager manager = WebAsyncUtils.getAsyncManager(new MockHttpServletRequest());
try {
manager.startCallableProcessing(new StubCallable(1));
fail("Expected exception");
}
catch (IllegalStateException ex) {
assertEquals("AsyncWebRequest must not be null", ex.getMessage());
}
assertThatIllegalStateException().isThrownBy(() ->
manager.startCallableProcessing(new StubCallable(1)))
.withMessage("AsyncWebRequest must not be null");
try {
manager.startDeferredResultProcessing(new DeferredResult<String>());
fail("Expected exception");
}
catch (IllegalStateException ex) {
assertEquals("AsyncWebRequest must not be null", ex.getMessage());
}
assertThatIllegalStateException().isThrownBy(() ->
manager.startDeferredResultProcessing(new DeferredResult<String>()))
.withMessage("AsyncWebRequest must not be null");
}
@Test
@@ -98,10 +92,11 @@ public class WebAsyncManagerTests {
assertTrue(this.asyncManager.isConcurrentHandlingStarted());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setAsyncWebRequestAfterAsyncStarted() {
this.asyncWebRequest.startAsync();
this.asyncManager.setAsyncWebRequest(null);
assertThatIllegalArgumentException().isThrownBy(() ->
this.asyncManager.setAsyncWebRequest(null));
}
@Test
@@ -148,7 +143,6 @@ public class WebAsyncManagerTests {
verify(interceptor).postProcess(this.asyncWebRequest, task, concurrentResult);
}
@SuppressWarnings("unchecked")
@Test
public void startCallableProcessingBeforeConcurrentHandlingException() throws Exception {
Callable<Object> task = new StubCallable(21);
@@ -159,13 +153,9 @@ public class WebAsyncManagerTests {
this.asyncManager.registerCallableInterceptor("interceptor", interceptor);
try {
this.asyncManager.startCallableProcessing(task);
fail("Expected Exception");
}
catch (Exception ex) {
assertEquals(exception, ex);
}
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
this.asyncManager.startCallableProcessing(task))
.isEqualTo(exception);
assertFalse(this.asyncManager.hasConcurrentResult());
@@ -259,13 +249,9 @@ public class WebAsyncManagerTests {
@Test
public void startCallableProcessingNullInput() throws Exception {
try {
this.asyncManager.startCallableProcessing((Callable<?>) null);
fail("Expected exception");
}
catch (IllegalArgumentException ex) {
assertEquals("Callable must not be null", ex.getMessage());
}
assertThatIllegalArgumentException().isThrownBy(() ->
this.asyncManager.startCallableProcessing((Callable<?>) null))
.withMessage("Callable must not be null");
}
@Test
@@ -290,7 +276,6 @@ public class WebAsyncManagerTests {
verify(this.asyncWebRequest).setTimeout(1000L);
}
@SuppressWarnings("unchecked")
@Test
public void startDeferredResultProcessingBeforeConcurrentHandlingException() throws Exception {
DeferredResult<Integer> deferredResult = new DeferredResult<>();
@@ -301,13 +286,9 @@ public class WebAsyncManagerTests {
this.asyncManager.registerDeferredResultInterceptor("interceptor", interceptor);
try {
this.asyncManager.startDeferredResultProcessing(deferredResult);
fail("Expected Exception");
}
catch (Exception success) {
assertEquals(exception, success);
}
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
this.asyncManager.startDeferredResultProcessing(deferredResult))
.isEqualTo(exception);
assertFalse(this.asyncManager.hasConcurrentResult());
@@ -360,13 +341,9 @@ public class WebAsyncManagerTests {
@Test
public void startDeferredResultProcessingNullInput() throws Exception {
try {
this.asyncManager.startDeferredResultProcessing(null);
fail("Expected exception");
}
catch (IllegalArgumentException ex) {
assertEquals("DeferredResult must not be null", ex.getMessage());
}
assertThatIllegalArgumentException().isThrownBy(() ->
this.asyncManager.startDeferredResultProcessing(null))
.withMessage("DeferredResult must not be null");
}
private void setupDefaultAsyncScenario() {
@@ -374,7 +351,6 @@ public class WebAsyncManagerTests {
given(this.asyncWebRequest.isAsyncComplete()).willReturn(false);
}
@SuppressWarnings("unchecked")
private void verifyDefaultAsyncScenario() {
verify(this.asyncWebRequest).addTimeoutHandler(notNull());
verify(this.asyncWebRequest).addErrorHandler(notNull());

View File

@@ -25,8 +25,7 @@ import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.ContextLoaderListener;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests the interaction between a WebApplicationContext and ContextLoaderListener with
@@ -47,15 +46,9 @@ public class Spr8510Tests {
MockServletContext sc = new MockServletContext();
try {
cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception");
}
catch (Throwable t) {
// assert that an attempt was made to load the correct XML
assertTrue(t.getMessage(), t.getMessage().endsWith(
"Could not open ServletContext resource [/programmatic.xml]"));
}
assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
cll.contextInitialized(new ServletContextEvent(sc)))
.withMessageEndingWith("Could not open ServletContext resource [/programmatic.xml]");
}
/**
@@ -74,15 +67,9 @@ public class Spr8510Tests {
MockServletContext sc = new MockServletContext();
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");
try {
cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception");
}
catch (Throwable t) {
// assert that an attempt was made to load the correct XML
assertTrue(t.getMessage(), t.getMessage().endsWith(
"Could not open ServletContext resource [/from-init-param.xml]"));
}
assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
cll.contextInitialized(new ServletContextEvent(sc)))
.withMessageEndingWith("Could not open ServletContext resource [/from-init-param.xml]");
}
/**
@@ -98,15 +85,9 @@ public class Spr8510Tests {
MockServletContext sc = new MockServletContext();
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");
try {
cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception");
}
catch (Throwable t) {
// assert that an attempt was made to load the correct XML
assertTrue(t.getMessage().endsWith(
"Could not open ServletContext resource [/from-init-param.xml]"));
}
assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
cll.contextInitialized(new ServletContextEvent(sc)))
.withMessageEndingWith("Could not open ServletContext resource [/from-init-param.xml]");
}
/**
@@ -126,16 +107,9 @@ public class Spr8510Tests {
MockServletContext sc = new MockServletContext();
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");
try {
cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception");
}
catch (Throwable t) {
// assert that an attempt was made to load the correct XML
System.out.println(t.getMessage());
assertTrue(t.getMessage().endsWith(
"Could not open ServletContext resource [/from-init-param.xml]"));
}
assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
cll.contextInitialized(new ServletContextEvent(sc)))
.withMessageEndingWith("Could not open ServletContext resource [/from-init-param.xml]");
}
/**
@@ -152,16 +126,9 @@ public class Spr8510Tests {
// no init-param set
//sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");
try {
cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception");
}
catch (Throwable t) {
// assert that an attempt was made to load the correct XML
System.out.println(t.getMessage());
assertTrue(t.getMessage().endsWith(
"Could not open ServletContext resource [/WEB-INF/applicationContext.xml]"));
}
assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
cll.contextInitialized(new ServletContextEvent(sc)))
.withMessageEndingWith("Could not open ServletContext resource [/WEB-INF/applicationContext.xml]");
}
/**

View File

@@ -24,6 +24,7 @@ import org.junit.Test;
import org.springframework.http.HttpMethod;
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.assertNull;
@@ -72,16 +73,18 @@ public class CorsConfigurationTests {
assertEquals(new Long(123), config.getMaxAge());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void asteriskWildCardOnAddExposedHeader() {
CorsConfiguration config = new CorsConfiguration();
config.addExposedHeader("*");
assertThatIllegalArgumentException().isThrownBy(() ->
config.addExposedHeader("*"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void asteriskWildCardOnSetExposedHeaders() {
CorsConfiguration config = new CorsConfiguration();
config.setExposedHeaders(Arrays.asList("*"));
assertThatIllegalArgumentException().isThrownBy(() ->
config.setExposedHeaders(Arrays.asList("*")));
}
@Test

View File

@@ -21,6 +21,7 @@ import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.mock.web.test.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@@ -50,9 +51,10 @@ public class UrlBasedCorsConfigurationSourceTests {
assertEquals(config, this.configSource.getCorsConfiguration(request));
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void unmodifiableConfigurationsMap() {
this.configSource.getCorsConfigurations().put("/**", new CorsConfiguration());
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
this.configSource.getCorsConfigurations().put("/**", new CorsConfiguration()));
}
}

View File

@@ -34,6 +34,7 @@ import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.StaticWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@@ -174,7 +175,7 @@ public class DelegatingFilterProxyTests {
assertNull(targetFilter.filterConfig);
}
@Test(expected = IllegalStateException.class)
@Test
public void testDelegatingFilterProxyWithTargetBeanNameAndNoApplicationContext()
throws ServletException, IOException {
@@ -185,7 +186,8 @@ public class DelegatingFilterProxyTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filterProxy.doFilter(request, response, null); // throws
assertThatIllegalStateException().isThrownBy(() ->
filterProxy.doFilter(request, response, null));
}
@Test

View File

@@ -29,6 +29,7 @@ import org.springframework.mock.web.test.MockFilterChain;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
@@ -45,14 +46,16 @@ public class RelativeRedirectFilterTests {
private HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
@Test(expected = IllegalArgumentException.class)
@Test
public void sendRedirectHttpStatusWhenNullThenIllegalArgumentException() {
this.filter.setRedirectStatus(null);
assertThatIllegalArgumentException().isThrownBy(() ->
this.filter.setRedirectStatus(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void sendRedirectHttpStatusWhenNot3xxThenIllegalArgumentException() {
this.filter.setRedirectStatus(HttpStatus.OK);
assertThatIllegalArgumentException().isThrownBy(() ->
this.filter.setRedirectStatus(HttpStatus.OK));
}
@Test

View File

@@ -31,10 +31,11 @@ import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
/**
* @author Rod Johnson
@@ -84,21 +85,14 @@ public class RequestContextFilterTests {
try {
rbf.doFilter(req, resp, fc);
if (sex != null) {
fail();
}
assertThat(sex).isNull();
}
catch (ServletException ex) {
assertNotNull(sex);
}
try {
RequestContextHolder.currentRequestAttributes();
fail();
}
catch (IllegalStateException ex) {
// Ok
}
assertThatIllegalStateException().isThrownBy(
RequestContextHolder::currentRequestAttributes);
assertEquals(1, fc.invocations);
}

View File

@@ -31,10 +31,10 @@ import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
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;
import static org.junit.Assert.fail;
/**
* Test fixture with {@link org.springframework.web.method.annotation.AbstractCookieValueMethodArgumentResolver}.
@@ -86,10 +86,10 @@ public class CookieValueMethodArgumentResolverTests {
assertEquals("Invalid result", "bar", result);
}
@Test(expected = ServletRequestBindingException.class)
@Test
public void notFound() throws Exception {
resolver.resolveArgument(paramNamedCookie, null, webRequest, null);
fail("Expected exception");
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
resolver.resolveArgument(paramNamedCookie, null, webRequest, null));
}
private static class TestCookieValueMethodArgumentResolver extends AbstractCookieValueMethodArgumentResolver {

View File

@@ -28,6 +28,7 @@ import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertSame;
/**
@@ -73,18 +74,20 @@ public class ErrorsMethodArgumentResolverTests {
assertSame(actual, bindingResult);
}
@Test(expected = IllegalStateException.class)
@Test
public void bindingResultNotFound() throws Exception {
ModelAndViewContainer mavContainer = new ModelAndViewContainer();
mavContainer.addAllAttributes(bindingResult.getModel());
mavContainer.addAttribute("ignore1", "value1");
resolver.resolveArgument(paramErrors, mavContainer, webRequest, null);
assertThatIllegalStateException().isThrownBy(() ->
resolver.resolveArgument(paramErrors, mavContainer, webRequest, null));
}
@Test(expected = IllegalStateException.class)
@Test
public void noBindingResult() throws Exception {
resolver.resolveArgument(paramErrors, new ModelAndViewContainer(), webRequest, null);
assertThatIllegalStateException().isThrownBy(() ->
resolver.resolveArgument(paramErrors, new ModelAndViewContainer(), webRequest, null));
}

View File

@@ -29,6 +29,7 @@ import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@@ -84,14 +85,16 @@ public class ExceptionHandlerMethodResolverTests {
assertEquals("handleIOException", resolver.resolveMethod(exception).getName());
}
@Test(expected = IllegalStateException.class)
@Test
public void ambiguousExceptionMapping() {
new ExceptionHandlerMethodResolver(AmbiguousController.class);
assertThatIllegalStateException().isThrownBy(() ->
new ExceptionHandlerMethodResolver(AmbiguousController.class));
}
@Test(expected = IllegalStateException.class)
@Test
public void noExceptionMapping() {
new ExceptionHandlerMethodResolver(NoExceptionController.class);
assertThatIllegalStateException().isThrownBy(() ->
new ExceptionHandlerMethodResolver(NoExceptionController.class));
}

View File

@@ -36,6 +36,7 @@ import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolverComposite;
import org.springframework.web.method.support.InvocableHandlerMethod;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -102,10 +103,11 @@ public class InitBinderDataBinderFactoryTests {
assertNull(dataBinder.getDisallowedFields());
}
@Test(expected = IllegalStateException.class)
@Test
public void returnValueNotExpected() throws Exception {
WebDataBinderFactory factory = createFactory("initBinderReturnValue", WebDataBinder.class);
factory.createBinder(this.webRequest, null, "invalidName");
assertThatIllegalStateException().isThrownBy(() ->
factory.createBinder(this.webRequest, null, "invalidName"));
}
@Test

View File

@@ -45,6 +45,7 @@ import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
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.assertSame;
@@ -216,7 +217,7 @@ public class ModelAttributeMethodProcessorTests {
assertTrue(dataBinder.isValidateInvoked());
}
@Test(expected = BindException.class)
@Test
public void resolveArgumentBindException() throws Exception {
String name = "testBean";
Object target = new TestBean();
@@ -227,7 +228,8 @@ public class ModelAttributeMethodProcessorTests {
WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
given(binderFactory.createBinder(this.request, target, name)).willReturn(dataBinder);
this.processor.resolveArgument(this.paramNonSimpleType, this.container, this.request, binderFactory);
assertThatExceptionOfType(BindException.class).isThrownBy(() ->
this.processor.resolveArgument(this.paramNonSimpleType, this.container, this.request, binderFactory));
verify(binderFactory).createBinder(this.request, target, name);
}

View File

@@ -41,11 +41,11 @@ import org.springframework.web.method.support.HandlerMethodArgumentResolverCompo
import org.springframework.web.method.support.InvocableHandlerMethod;
import org.springframework.web.method.support.ModelAndViewContainer;
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.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -153,13 +153,8 @@ public class ModelFactoryTests {
public void sessionAttributeNotPresent() throws Exception {
ModelFactory modelFactory = new ModelFactory(null, null, this.attributeHandler);
HandlerMethod handlerMethod = createHandlerMethod("handleSessionAttr", String.class);
try {
modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod);
fail("Expected HttpSessionRequiredException");
}
catch (HttpSessionRequiredException ex) {
// expected
}
assertThatExceptionOfType(HttpSessionRequiredException.class).isThrownBy(() ->
modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod));
// Now add attribute and try again
this.attributeStore.storeAttribute(this.webRequest, "sessionAttr", "sessionAttrValue");

View File

@@ -41,6 +41,7 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.support.GenericWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -190,9 +191,10 @@ public class RequestHeaderMethodArgumentResolverTests {
assertEquals("/bar", result);
}
@Test(expected = ServletRequestBindingException.class)
@Test
public void notFound() throws Exception {
resolver.resolveArgument(paramNamedValueStringArray, null, webRequest, null);
assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() ->
resolver.resolveArgument(paramNamedValueStringArray, null, webRequest, null));
}
@Test

View File

@@ -47,12 +47,12 @@ import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.web.method.MvcAnnotationPredicates.requestParam;
@@ -305,11 +305,11 @@ public class RequestParamMethodArgumentResolverTests {
assertEquals(Arrays.asList(expected1, expected2), result);
}
@Test(expected = MultipartException.class)
@Test
public void isMultipartRequest() throws Exception {
MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(MultipartFile.class);
resolver.resolveArgument(param, null, webRequest, null);
fail("Expected exception: request is not a multipart request");
assertThatExceptionOfType(MultipartException.class).isThrownBy(() ->
resolver.resolveArgument(param, null, webRequest, null));
}
@Test // SPR-9079
@@ -328,21 +328,21 @@ public class RequestParamMethodArgumentResolverTests {
assertEquals(expected, ((List<?>) actual).get(0));
}
@Test(expected = MultipartException.class)
@Test
public void noMultipartContent() throws Exception {
request.setMethod("POST");
MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(MultipartFile.class);
resolver.resolveArgument(param, null, webRequest, null);
fail("Expected exception: no multipart content");
assertThatExceptionOfType(MultipartException.class).isThrownBy(() ->
resolver.resolveArgument(param, null, webRequest, null));
}
@Test(expected = MissingServletRequestPartException.class)
@Test
public void missingMultipartFile() throws Exception {
request.setMethod("POST");
request.setContentType("multipart/form-data");
MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(MultipartFile.class);
resolver.resolveArgument(param, null, webRequest, null);
fail("Expected exception: no such part found");
assertThatExceptionOfType(MissingServletRequestPartException.class).isThrownBy(() ->
resolver.resolveArgument(param, null, webRequest, null));
}
@Test
@@ -368,11 +368,11 @@ public class RequestParamMethodArgumentResolverTests {
assertEquals("Invalid result", "bar", result);
}
@Test(expected = MissingServletRequestParameterException.class)
@Test
public void missingRequestParam() throws Exception {
MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(String[].class);
resolver.resolveArgument(param, null, webRequest, null);
fail("Expected exception");
assertThatExceptionOfType(MissingServletRequestParameterException.class).isThrownBy(() ->
resolver.resolveArgument(param, null, webRequest, null));
}
@Test // SPR-10578

View File

@@ -27,6 +27,8 @@ import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletWebRequest;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
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.assertTrue;
@@ -111,25 +113,28 @@ public class WebArgumentResolverAdapterTests {
assertEquals("Invalid result", expected, result);
}
@Test(expected = IllegalStateException.class)
@Test
public void resolveArgumentUnresolved() throws Exception {
given(adaptee.resolveArgument(parameter, webRequest)).willReturn(WebArgumentResolver.UNRESOLVED);
adapter.resolveArgument(parameter, null, webRequest, null);
assertThatIllegalStateException().isThrownBy(() ->
adapter.resolveArgument(parameter, null, webRequest, null));
}
@Test(expected = IllegalStateException.class)
@Test
public void resolveArgumentWrongType() throws Exception {
given(adaptee.resolveArgument(parameter, webRequest)).willReturn("Foo");
adapter.resolveArgument(parameter, null, webRequest, null);
assertThatIllegalStateException().isThrownBy(() ->
adapter.resolveArgument(parameter, null, webRequest, null));
}
@Test(expected = Exception.class)
@Test
public void resolveArgumentThrowsException() throws Exception {
given(adaptee.resolveArgument(parameter, webRequest)).willThrow(new Exception());
adapter.resolveArgument(parameter, null, webRequest, null);
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
adapter.resolveArgument(parameter, null, webRequest, null));
}
public void handle(int param) {

View File

@@ -23,6 +23,7 @@ import org.junit.Test;
import org.springframework.core.MethodParameter;
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.assertTrue;
@@ -76,9 +77,10 @@ public class HandlerMethodArgumentResolverCompositeTests {
assertEquals("Didn't use the first registered resolver", 1, resolvedValue);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void noSuitableArgumentResolver() throws Exception {
this.resolverComposite.resolveArgument(paramStr, null, null, null);
assertThatIllegalArgumentException().isThrownBy(() ->
this.resolverComposite.resolveArgument(paramStr, null, null, null));
}

View File

@@ -21,6 +21,7 @@ import org.junit.Test;
import org.springframework.core.MethodParameter;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
@@ -108,9 +109,10 @@ public class HandlerMethodReturnValueHandlerCompositeTests {
verifyNoMoreInteractions(responseBodyHandler);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void noSuitableReturnValueHandler() throws Exception {
this.handlers.handleReturnValue("value", this.stringType, null, null);
assertThatIllegalArgumentException().isThrownBy(() ->
this.handlers.handleReturnValue("value", this.stringType, null, null));
}

View File

@@ -29,13 +29,11 @@ import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.ResolvableMethod;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for {@link InvocableHandlerMethod}.
@@ -83,13 +81,9 @@ public class InvocableHandlerMethodTests {
@Test
public void cannotResolveArg() throws Exception {
try {
getInvocable(Integer.class, String.class).invokeForRequest(request, null);
fail("Expected exception");
}
catch (IllegalStateException ex) {
assertTrue(ex.getMessage().contains("Could not resolve parameter [0]"));
}
assertThatIllegalStateException().isThrownBy(() ->
getInvocable(Integer.class, String.class).invokeForRequest(request, null))
.withMessageContaining("Could not resolve parameter [0]");
}
@Test
@@ -113,85 +107,54 @@ public class InvocableHandlerMethodTests {
@Test
public void exceptionInResolvingArg() throws Exception {
this.composite.addResolver(new ExceptionRaisingArgumentResolver());
try {
getInvocable(Integer.class, String.class).invokeForRequest(request, null);
fail("Expected exception");
}
catch (IllegalArgumentException ex) {
// expected - allow HandlerMethodArgumentResolver exceptions to propagate
}
assertThatIllegalArgumentException().isThrownBy(() ->
getInvocable(Integer.class, String.class).invokeForRequest(request, null));
}
@Test
public void illegalArgumentException() throws Exception {
this.composite.addResolver(new StubArgumentResolver(Integer.class, "__not_an_int__"));
this.composite.addResolver(new StubArgumentResolver("value"));
try {
getInvocable(Integer.class, String.class).invokeForRequest(request, null);
fail("Expected exception");
}
catch (IllegalStateException ex) {
assertNotNull("Exception not wrapped", ex.getCause());
assertTrue(ex.getCause() instanceof IllegalArgumentException);
assertTrue(ex.getMessage().contains("Controller ["));
assertTrue(ex.getMessage().contains("Method ["));
assertTrue(ex.getMessage().contains("with argument values:"));
assertTrue(ex.getMessage().contains("[0] [type=java.lang.String] [value=__not_an_int__]"));
assertTrue(ex.getMessage().contains("[1] [type=java.lang.String] [value=value"));
}
assertThatIllegalStateException().isThrownBy(() ->
getInvocable(Integer.class, String.class).invokeForRequest(request, null))
.withCauseInstanceOf(IllegalArgumentException.class)
.withMessageContaining("Controller [")
.withMessageContaining("Method [")
.withMessageContaining("with argument values:")
.withMessageContaining("[0] [type=java.lang.String] [value=__not_an_int__]")
.withMessageContaining("[1] [type=java.lang.String] [value=value");
}
@Test
public void invocationTargetException() throws Exception {
Throwable expected = new RuntimeException("error");
try {
getInvocable(Throwable.class).invokeForRequest(this.request, null, expected);
fail("Expected exception");
}
catch (RuntimeException actual) {
assertSame(expected, actual);
}
RuntimeException runtimeException = new RuntimeException("error");
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
getInvocable(Throwable.class).invokeForRequest(this.request, null, runtimeException))
.isSameAs(runtimeException);
expected = new Error("error");
try {
getInvocable(Throwable.class).invokeForRequest(this.request, null, expected);
fail("Expected exception");
}
catch (Error actual) {
assertSame(expected, actual);
}
Error error = new Error("error");
assertThatExceptionOfType(Error.class).isThrownBy(() ->
getInvocable(Throwable.class).invokeForRequest(this.request, null, error))
.isSameAs(error);
expected = new Exception("error");
try {
getInvocable(Throwable.class).invokeForRequest(this.request, null, expected);
fail("Expected exception");
}
catch (Exception actual) {
assertSame(expected, actual);
}
Exception exception = new Exception("error");
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
getInvocable(Throwable.class).invokeForRequest(this.request, null, exception))
.isSameAs(exception);
expected = new Throwable("error");
try {
getInvocable(Throwable.class).invokeForRequest(this.request, null, expected);
fail("Expected exception");
}
catch (IllegalStateException actual) {
assertNotNull(actual.getCause());
assertSame(expected, actual.getCause());
assertTrue(actual.getMessage().contains("Invocation failure"));
}
Throwable throwable = new Throwable("error");
assertThatIllegalStateException().isThrownBy(() ->
getInvocable(Throwable.class).invokeForRequest(this.request, null, throwable))
.withCause(throwable)
.withMessageContaining("Invocation failure");
}
@Test // SPR-13917
public void invocationErrorMessage() throws Exception {
this.composite.addResolver(new StubArgumentResolver(double.class));
try {
getInvocable(double.class).invokeForRequest(this.request, null);
fail();
}
catch (IllegalStateException ex) {
assertThat(ex.getMessage(), containsString("Illegal argument"));
}
assertThatIllegalStateException().isThrownBy(() ->
getInvocable(double.class).invokeForRequest(this.request, null))
.withMessageContaining("Illegal argument");
}
private InvocableHandlerMethod getInvocable(Class<?>... argTypes) {

View File

@@ -22,6 +22,7 @@ import org.junit.Test;
import org.springframework.web.multipart.MultipartFile;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -77,11 +78,12 @@ public class ByteArrayMultipartFileEditorTests {
assertEquals(expectedValue, editor.getAsText());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setValueAsMultipartFileWithBadBytes() throws Exception {
MultipartFile file = mock(MultipartFile.class);
given(file.getBytes()).willThrow(new IOException());
editor.setValue(file);
assertThatIllegalArgumentException().isThrownBy(() ->
editor.setValue(file));
}
}

View File

@@ -25,6 +25,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.web.test.server.MockServerWebExchange;
import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -106,11 +107,10 @@ public class HeaderWebSessionIdResolverTests {
this.exchange.getResponse().getHeaders().get(headerName));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setSessionIdWhenNullIdThenIllegalArgumentException() {
String id = null;
this.idResolver.setSessionId(this.exchange, id);
assertThatIllegalArgumentException().isThrownBy(() ->
this.idResolver.setSessionId(this.exchange, (String) null));
}
@Test

View File

@@ -27,12 +27,12 @@ import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.web.server.WebSession;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for {@link InMemoryWebSessionStore}.
@@ -149,14 +149,9 @@ public class InMemoryWebSessionStoreTests {
public void maxSessions() {
IntStream.range(0, 10000).forEach(i -> insertSession());
try {
insertSession();
fail();
}
catch (IllegalStateException ex) {
assertEquals("Max sessions limit reached: 10000", ex.getMessage());
}
assertThatIllegalStateException().isThrownBy(
this::insertSession)
.withMessage("Max sessions limit reached: 10000");
}
private WebSession insertSession() {

View File

@@ -21,10 +21,10 @@ import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.util.FileCopyUtils;
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.assertFalse;
import static org.junit.Assert.fail;
/**
* @author Brian Clozel
@@ -74,13 +74,9 @@ public class ContentCachingRequestWrapperTests {
}
};
try {
FileCopyUtils.copyToByteArray(wrapper.getInputStream());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
assertEquals("3", ex.getMessage());
}
assertThatIllegalStateException().isThrownBy(() ->
FileCopyUtils.copyToByteArray(wrapper.getInputStream()))
.withMessage("3");
}
@Test

View File

@@ -22,6 +22,8 @@ import javax.servlet.jsp.tagext.TagSupport;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
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.assertTrue;
@@ -52,24 +54,28 @@ public class TagUtilsTests {
TagUtils.getScope("bla"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void getScopeWithNullScopeArgument() {
TagUtils.getScope(null);
assertThatIllegalArgumentException().isThrownBy(() ->
TagUtils.getScope(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void hasAncestorOfTypeWhereAncestorTagIsNotATagType() throws Exception {
assertFalse(TagUtils.hasAncestorOfType(new TagSupport(), String.class));
assertThatIllegalArgumentException().isThrownBy(() ->
TagUtils.hasAncestorOfType(new TagSupport(), String.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void hasAncestorOfTypeWithNullTagArgument() throws Exception {
assertFalse(TagUtils.hasAncestorOfType(null, TagSupport.class));
assertThatIllegalArgumentException().isThrownBy(() ->
TagUtils.hasAncestorOfType(null, TagSupport.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void hasAncestorOfTypeWithNullAncestorTagClassArgument() throws Exception {
assertFalse(TagUtils.hasAncestorOfType(new TagSupport(), null));
assertThatIllegalArgumentException().isThrownBy(() ->
TagUtils.hasAncestorOfType(new TagSupport(), null));
}
@Test
@@ -101,26 +107,29 @@ public class TagUtilsTests {
assertFalse(TagUtils.hasAncestorOfType(new TagA(), TagC.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void assertHasAncestorOfTypeWithNullTagName() throws Exception {
TagUtils.assertHasAncestorOfType(new TagA(), TagC.class, null, "c");
assertThatIllegalArgumentException().isThrownBy(() ->
TagUtils.assertHasAncestorOfType(new TagA(), TagC.class, null, "c"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void assertHasAncestorOfTypeWithNullAncestorTagName() throws Exception {
TagUtils.assertHasAncestorOfType(new TagA(), TagC.class, "a", null);
assertThatIllegalArgumentException().isThrownBy(() ->
TagUtils.assertHasAncestorOfType(new TagA(), TagC.class, "a", null));
}
@Test(expected = IllegalStateException.class)
@Test
public void assertHasAncestorOfTypeThrowsExceptionOnFail() throws Exception {
Tag a = new TagA();
Tag b = new TagB();
Tag anotherB = new TagB();
Tag a = new TagA();
Tag b = new TagB();
Tag anotherB = new TagB();
a.setParent(b);
b.setParent(anotherB);
a.setParent(b);
b.setParent(anotherB);
TagUtils.assertHasAncestorOfType(a, TagC.class, "a", "c");
assertThatIllegalStateException().isThrownBy(() ->
TagUtils.assertHasAncestorOfType(a, TagC.class, "a", "c"));
}
@Test

View File

@@ -33,6 +33,7 @@ import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
@@ -216,9 +217,10 @@ public class UriComponentsBuilderTests {
assertEquals("https", UriComponentsBuilder.fromHttpUrl("HTTPS://www.google.com").build().getScheme());
}
@Test(expected = IllegalArgumentException.class) // SPR-10539
@Test // SPR-10539
public void fromHttpUrlStringInvalidIPv6Host() {
UriComponentsBuilder.fromHttpUrl("http://[1abc:2abc:3abc::5ABC:6abc:8080/resource").build().encode();
assertThatIllegalArgumentException().isThrownBy(() ->
UriComponentsBuilder.fromHttpUrl("http://[1abc:2abc:3abc::5ABC:6abc:8080/resource").build().encode());
}
@Test // SPR-10539

View File

@@ -27,6 +27,8 @@ import java.util.Collections;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
@@ -158,19 +160,22 @@ public class UriComponentsTests {
assertEquals("https://example.com:8080/bar", uri4.toUriString());
}
@Test(expected = IllegalStateException.class)
@Test
public void expandEncoded() {
UriComponentsBuilder.fromPath("/{foo}").build().encode().expand("bar");
assertThatIllegalStateException().isThrownBy(() ->
UriComponentsBuilder.fromPath("/{foo}").build().encode().expand("bar"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void invalidCharacters() {
UriComponentsBuilder.fromPath("/{foo}").build(true);
assertThatIllegalArgumentException().isThrownBy(() ->
UriComponentsBuilder.fromPath("/{foo}").build(true));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void invalidEncodedSequence() {
UriComponentsBuilder.fromPath("/fo%2o").build(true);
assertThatIllegalArgumentException().isThrownBy(() ->
UriComponentsBuilder.fromPath("/fo%2o").build(true));
}
@Test

View File

@@ -25,6 +25,7 @@ import java.util.Map;
import org.junit.Test;
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.assertTrue;
@@ -59,10 +60,11 @@ public class UriTemplateTests {
assertEquals(new URI("/sum?numbers=1,2,3"), result);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void expandVarArgsNotEnoughVariables() throws Exception {
UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}");
template.expand("1");
assertThatIllegalArgumentException().isThrownBy(() ->
template.expand("1"));
}
@Test
@@ -101,13 +103,14 @@ public class UriTemplateTests {
assertEquals("Invalid expanded template", new URI("/hotel%20list/Z%C3%BCrich"), result);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void expandMapUnboundVariables() throws Exception {
Map<String, String> uriVariables = new HashMap<>(2);
uriVariables.put("booking", "42");
uriVariables.put("bar", "1");
UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}");
template.expand(uriVariables);
assertThatIllegalArgumentException().isThrownBy(() ->
template.expand(uriVariables));
}
@Test

View File

@@ -21,6 +21,7 @@ import java.nio.charset.StandardCharsets;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
/**
@@ -109,9 +110,10 @@ public class UriUtilsTests {
assertEquals("Invalid encoded result", "T\u014dky\u014d", UriUtils.decode("T\u014dky\u014d", CHARSET));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void decodeInvalidSequence() {
UriUtils.decode("foo%2", CHARSET);
assertThatIllegalArgumentException().isThrownBy(() ->
UriUtils.decode("foo%2", CHARSET));
}
@Test

View File

@@ -25,6 +25,9 @@ import org.junit.Test;
import org.springframework.http.server.PathContainer;
import org.springframework.web.util.pattern.PatternParseException.PatternMessage;
import static org.assertj.core.api.Assertions.assertThat;
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.assertFalse;
import static org.junit.Assert.assertNotEquals;
@@ -242,20 +245,12 @@ public class PathPatternParserTests {
checkError("/foobar/{abc}_{abc}", 8, PatternMessage.ILLEGAL_DOUBLE_CAPTURE);
checkError("/foobar/{abc:..}_{abc:..}", 8, PatternMessage.ILLEGAL_DOUBLE_CAPTURE);
PathPattern pp = parse("/{abc:foo(bar)}");
try {
pp.matchAndExtract(toPSC("/foo"));
fail("Should have raised exception");
}
catch (IllegalArgumentException iae) {
assertEquals("No capture groups allowed in the constraint regex: foo(bar)", iae.getMessage());
}
try {
pp.matchAndExtract(toPSC("/foobar"));
fail("Should have raised exception");
}
catch (IllegalArgumentException iae) {
assertEquals("No capture groups allowed in the constraint regex: foo(bar)", iae.getMessage());
}
assertThatIllegalArgumentException().isThrownBy(() ->
pp.matchAndExtract(toPSC("/foo")))
.withMessage("No capture groups allowed in the constraint regex: foo(bar)");
assertThatIllegalArgumentException().isThrownBy(() ->
pp.matchAndExtract(toPSC("/foobar")))
.withMessage("No capture groups allowed in the constraint regex: foo(bar)");
}
@Test
@@ -432,20 +427,15 @@ public class PathPatternParserTests {
private void checkError(String pattern, int expectedPos, PatternMessage expectedMessage,
String... expectedInserts) {
try {
pathPattern = parse(pattern);
fail("Expected to fail");
}
catch (PatternParseException ppe) {
assertEquals(ppe.toDetailedString(), expectedPos, ppe.getPosition());
assertEquals(ppe.toDetailedString(), expectedMessage, ppe.getMessageType());
assertThatExceptionOfType(PatternParseException.class).isThrownBy(() ->
pathPattern = parse(pattern))
.satisfies(ex -> {
assertEquals(ex.toDetailedString(), expectedPos, ex.getPosition());
assertEquals(ex.toDetailedString(), expectedMessage, ex.getMessageType());
if (expectedInserts.length != 0) {
assertEquals(ppe.getInserts().length, expectedInserts.length);
for (int i = 0; i < expectedInserts.length; i++) {
assertEquals("Insert at position " + i + " is wrong", expectedInserts[i], ppe.getInserts()[i]);
}
assertThat(ex.getInserts()).isEqualTo(expectedInserts);
}
}
});
}
@SafeVarargs

View File

@@ -31,6 +31,7 @@ import org.springframework.http.server.PathContainer.Element;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.util.pattern.PathPattern.PathRemainingMatchInfo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
@@ -38,7 +39,6 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Exercise matching of {@link PathPattern} objects.
@@ -1180,14 +1180,7 @@ public class PathPatternTests {
}
for (Map.Entry<String, String> me : expectedKeyValues.entrySet()) {
String value = matchResult.getUriVariables().get(me.getKey());
if (value == null) {
fail("Did not find key '" + me.getKey() + "' in captured variables: "
+ matchResult.getUriVariables());
}
if (!value.equals(me.getValue())) {
fail("Expected value '" + me.getValue() + "' for key '" + me.getKey()
+ "' but was '" + value + "'");
}
assertThat(value).as("value for " + me.getKey()).isEqualTo(me.getValue());
}
return matchResult;
}