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

@@ -39,11 +39,12 @@ import org.junit.Test;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
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.empty;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.fail;
import static org.springframework.core.CollectionFactory.createApproximateCollection;
import static org.springframework.core.CollectionFactory.createApproximateMap;
import static org.springframework.core.CollectionFactory.createCollection;
@@ -75,16 +76,13 @@ public class CollectionFactoryTests {
// Use a try-catch block to ensure that the exception is thrown as a result of the
// next line and not as a result of the previous line.
try {
// Note that ints is of type Collection<Integer>, but the collection returned
// by createApproximateCollection() is of type Collection<Color>. Thus, 42
// cannot be cast to a Color.
ints.add(42);
fail("Should have thrown a ClassCastException");
}
catch (ClassCastException e) {
/* expected */
}
// Note that ints is of type Collection<Integer>, but the collection returned
// by createApproximateCollection() is of type Collection<Color>. Thus, 42
// cannot be cast to a Color.
assertThatExceptionOfType(ClassCastException.class).isThrownBy(() ->
ints.add(42));
}
@Test
@@ -93,16 +91,13 @@ public class CollectionFactoryTests {
// Use a try-catch block to ensure that the exception is thrown as a result of the
// next line and not as a result of the previous line.
try {
// Note that ints is of type Collection<Integer>, but the collection returned
// by createCollection() is of type Collection<Color>. Thus, 42 cannot be cast
// to a Color.
ints.add(42);
fail("Should have thrown a ClassCastException");
}
catch (ClassCastException e) {
/* expected */
}
// Note that ints is of type Collection<Integer>, but the collection returned
// by createCollection() is of type Collection<Color>. Thus, 42 cannot be cast
// to a Color.
assertThatExceptionOfType(ClassCastException.class).isThrownBy(() ->
ints.add(42));
}
/**
@@ -121,16 +116,13 @@ public class CollectionFactoryTests {
// Use a try-catch block to ensure that the exception is thrown as a result of the
// next line and not as a result of the previous line.
try {
// Note that the 'map' key must be of type String, but the keys in the map
// returned by createApproximateMap() are of type Color. Thus "foo" cannot be
// cast to a Color.
map.put("foo", 1);
fail("Should have thrown a ClassCastException");
}
catch (ClassCastException e) {
/* expected */
}
// Note that the 'map' key must be of type String, but the keys in the map
// returned by createApproximateMap() are of type Color. Thus "foo" cannot be
// cast to a Color.
assertThatExceptionOfType(ClassCastException.class).isThrownBy(() ->
map.put("foo", 1));
}
@Test
@@ -139,16 +131,13 @@ public class CollectionFactoryTests {
// Use a try-catch block to ensure that the exception is thrown as a result of the
// next line and not as a result of the previous line.
try {
// Note that the 'map' key must be of type String, but the keys in the map
// returned by createMap() are of type Color. Thus "foo" cannot be cast to a
// Color.
map.put("foo", 1);
fail("Should have thrown a ClassCastException");
}
catch (ClassCastException e) {
/* expected */
}
// Note that the 'map' key must be of type String, but the keys in the map
// returned by createMap() are of type Color. Thus "foo" cannot be cast to a
// Color.
assertThatExceptionOfType(ClassCastException.class).isThrownBy(() ->
map.put("foo", 1));
}
@Test
@@ -157,16 +146,13 @@ public class CollectionFactoryTests {
// Use a try-catch block to ensure that the exception is thrown as a result of the
// next line and not as a result of the previous line.
try {
// Note: 'map' values must be of type Integer, but the values in the map
// returned by createMap() are of type java.util.List. Thus 1 cannot be
// cast to a List.
map.put("foo", 1);
fail("Should have thrown a ClassCastException");
}
catch (ClassCastException e) {
/* expected */
}
// Note: 'map' values must be of type Integer, but the values in the map
// returned by createMap() are of type java.util.List. Thus 1 cannot be
// cast to a List.
assertThatExceptionOfType(ClassCastException.class).isThrownBy(() ->
map.put("foo", 1));
}
@Test
@@ -254,19 +240,22 @@ public class CollectionFactoryTests {
assertThat(createCollection(enumSet.getClass(), Color.class, 0), is(instanceOf(enumSet.getClass())));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsInvalidElementTypeForEnumSet() {
createCollection(EnumSet.class, Object.class, 0);
assertThatIllegalArgumentException().isThrownBy(() ->
createCollection(EnumSet.class, Object.class, 0));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullElementTypeForEnumSet() {
createCollection(EnumSet.class, null, 0);
assertThatIllegalArgumentException().isThrownBy(() ->
createCollection(EnumSet.class, null, 0));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullCollectionType() {
createCollection(null, Object.class, 0);
assertThatIllegalArgumentException().isThrownBy(() ->
createCollection(null, Object.class, 0));
}
@Test
@@ -293,19 +282,22 @@ public class CollectionFactoryTests {
assertThat(createMap(EnumMap.class, Color.class, 0), is(instanceOf(EnumMap.class)));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsInvalidKeyTypeForEnumMap() {
createMap(EnumMap.class, Object.class, 0);
assertThatIllegalArgumentException().isThrownBy(() ->
createMap(EnumMap.class, Object.class, 0));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullKeyTypeForEnumMap() {
createMap(EnumMap.class, null, 0);
assertThatIllegalArgumentException().isThrownBy(() ->
createMap(EnumMap.class, null, 0));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullMapType() {
createMap(null, Object.class, 0);
assertThatIllegalArgumentException().isThrownBy(() ->
createMap(null, Object.class, 0));
}

View File

@@ -21,10 +21,11 @@ import java.util.Set;
import org.junit.Test;
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.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rod Johnson
@@ -44,20 +45,12 @@ public class ConstantsTests {
assertEquals(A.DOG, c.asNumber("dog").intValue());
assertEquals(A.CAT, c.asNumber("cat").intValue());
try {
c.asNumber("bogus");
fail("Can't get bogus field");
}
catch (Constants.ConstantException expected) {
}
assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() ->
c.asNumber("bogus"));
assertTrue(c.asString("S1").equals(A.S1));
try {
c.asNumber("S1");
fail("Wrong type");
}
catch (Constants.ConstantException expected) {
}
assertThatExceptionOfType(Constants.ConstantException.class).as("wrong type").isThrownBy(() ->
c.asNumber("S1"));
}
@Test
@@ -169,27 +162,15 @@ public class ConstantsTests {
assertEquals("S1", c.toCode("", "s"));
assertEquals("S1", c.toCode("", "s1"));
assertEquals("S1", c.toCode("", null));
try {
c.toCode("bogus", "bogus");
fail("Should have thrown ConstantException");
}
catch (Constants.ConstantException expected) {
}
try {
c.toCode("bogus", null);
fail("Should have thrown ConstantException");
}
catch (Constants.ConstantException expected) {
}
assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() ->
c.toCode("bogus", "bogus"));
assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() ->
c.toCode("bogus", null));
assertEquals("MY_PROPERTY_NO", c.toCodeForProperty(Integer.valueOf(1), "myProperty"));
assertEquals("MY_PROPERTY_YES", c.toCodeForProperty(Integer.valueOf(2), "myProperty"));
try {
c.toCodeForProperty("bogus", "bogus");
fail("Should have thrown ConstantException");
}
catch (Constants.ConstantException expected) {
}
assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() ->
c.toCodeForProperty("bogus", "bogus"));
assertEquals("DOG", c.toCodeForSuffix(Integer.valueOf(0), ""));
assertEquals("DOG", c.toCodeForSuffix(Integer.valueOf(0), "G"));
@@ -205,18 +186,10 @@ public class ConstantsTests {
assertEquals("S1", c.toCodeForSuffix("", "1"));
assertEquals("S1", c.toCodeForSuffix("", "s1"));
assertEquals("S1", c.toCodeForSuffix("", null));
try {
c.toCodeForSuffix("bogus", "bogus");
fail("Should have thrown ConstantException");
}
catch (Constants.ConstantException expected) {
}
try {
c.toCodeForSuffix("bogus", null);
fail("Should have thrown ConstantException");
}
catch (Constants.ConstantException expected) {
}
assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() ->
c.toCodeForSuffix("bogus", "bogus"));
assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() ->
c.toCodeForSuffix("bogus", null));
}
@Test
@@ -251,11 +224,8 @@ public class ConstantsTests {
@Test
public void ctorWithNullClass() throws Exception {
try {
new Constants(null);
fail("Must have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {}
assertThatIllegalArgumentException().isThrownBy(() ->
new Constants(null));
}

View File

@@ -27,6 +27,7 @@ import java.util.concurrent.Callable;
import org.junit.Before;
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.assertNotEquals;
@@ -104,9 +105,10 @@ public class MethodParameterTests {
assertEquals(longParameter, MethodParameter.forParameter(method.getParameters()[1]));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testIndexValidation() {
new MethodParameter(method, 2);
assertThatIllegalArgumentException().isThrownBy(() ->
new MethodParameter(method, 2));
}
@Test

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.assertNotEquals;
@@ -99,9 +100,10 @@ public class SynthesizingMethodParameterTests {
assertEquals(longParameter, SynthesizingMethodParameter.forParameter(method.getParameters()[1]));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testIndexValidation() {
new SynthesizingMethodParameter(method, 2);
assertThatIllegalArgumentException().isThrownBy(() ->
new SynthesizingMethodParameter(method, 2));
}

View File

@@ -33,7 +33,7 @@ import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.MimeType;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Abstract base class for {@link Decoder} unit tests. Subclasses need to implement
@@ -208,14 +208,9 @@ public abstract class AbstractDecoderTestCase<D extends Decoder<?>>
protected void testDecodeError(Publisher<DataBuffer> input, ResolvableType outputType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
input = Mono.from(input).concatWith(Flux.error(new InputException()));
try {
this.decoder.decode(input, outputType, mimeType, hints).blockLast(Duration.ofSeconds(5));
fail();
}
catch (InputException ex) {
// expected
}
Flux<DataBuffer> buffer = Mono.from(input).concatWith(Flux.error(new InputException()));
assertThatExceptionOfType(InputException.class).isThrownBy(() ->
this.decoder.decode(buffer, outputType, mimeType, hints).blockLast(Duration.ofSeconds(5)));
}
/**

View File

@@ -34,7 +34,6 @@ import org.springframework.util.StreamUtils;
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.springframework.core.ResolvableType.forClass;
/**
@@ -73,8 +72,8 @@ public class ResourceDecoderTests extends AbstractDecoderTestCase<ResourceDecode
byte[] bytes = StreamUtils.copyToByteArray(resource.getInputStream());
assertEquals("foobar", new String(bytes));
}
catch (IOException e) {
fail(e.getMessage());
catch (IOException ex) {
throw new AssertionError(ex.getMessage(), ex);
}
})
.expectComplete()
@@ -96,8 +95,8 @@ public class ResourceDecoderTests extends AbstractDecoderTestCase<ResourceDecode
assertEquals("foobar", new String(bytes));
assertEquals("testFile", resource.getFilename());
}
catch (IOException e) {
fail(e.getMessage());
catch (IOException ex) {
throw new AssertionError(ex.getMessage(), ex);
}
})
.expectComplete()

View File

@@ -42,6 +42,7 @@ import org.springframework.core.MethodParameter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
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.nullValue;
@@ -51,7 +52,6 @@ import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests for {@link TypeDescriptor}.
@@ -418,9 +418,10 @@ public class TypeDescriptorTests {
assertEquals(String.class, t1.getType());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void nestedMethodParameterNot1NestedLevel() throws Exception {
TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test4", List.class), 0, 2), 2);
assertThatIllegalArgumentException().isThrownBy(() ->
TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test4", List.class), 0, 2), 2));
}
@Test
@@ -435,9 +436,10 @@ public class TypeDescriptorTests {
assertNull(t1);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void nestedMethodParameterTypeInvalidNestingLevel() throws Exception {
TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test5", String.class), 0, 2), 2);
assertThatIllegalArgumentException().isThrownBy(() ->
TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test5", String.class), 0, 2), 2));
}
@Test
@@ -684,13 +686,9 @@ public class TypeDescriptorTests {
Property property = new Property(getClass(), getClass().getMethod("getProperty"),
getClass().getMethod("setProperty", Map.class));
TypeDescriptor typeDescriptor = new TypeDescriptor(property);
try {
typeDescriptor.upcast(Collection.class);
fail("Did not throw");
}
catch (IllegalArgumentException ex) {
assertEquals("interface java.util.Map is not assignable to interface java.util.Collection", ex.getMessage());
}
assertThatIllegalArgumentException().isThrownBy(() ->
typeDescriptor.upcast(Collection.class))
.withMessage("interface java.util.Map is not assignable to interface java.util.Collection");
}
@Test

View File

@@ -29,6 +29,7 @@ import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.util.comparator.ComparableComparator;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -46,25 +47,28 @@ public class ConvertingComparatorTests {
private final TestComparator comparator = new TestComparator();
@Test(expected = IllegalArgumentException.class)
@Test
public void shouldThrowOnNullComparator() throws Exception {
new ConvertingComparator<>(null, this.converter);
assertThatIllegalArgumentException().isThrownBy(() ->
new ConvertingComparator<>(null, this.converter));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void shouldThrowOnNullConverter() throws Exception {
new ConvertingComparator<String, Integer>(this.comparator, null);
assertThatIllegalArgumentException().isThrownBy(() ->
new ConvertingComparator<String, Integer>(this.comparator, null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void shouldThrowOnNullConversionService() throws Exception {
new ConvertingComparator<String, Integer>(this.comparator, null, Integer.class);
assertThatIllegalArgumentException().isThrownBy(() ->
new ConvertingComparator<String, Integer>(this.comparator, null, Integer.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void shouldThrowOnNullType() throws Exception {
new ConvertingComparator<String, Integer>(this.comparator,
this.conversionService, null);
assertThatIllegalArgumentException().isThrownBy(() ->
new ConvertingComparator<String, Integer>(this.comparator, this.conversionService, null));
}
@Test

View File

@@ -56,6 +56,7 @@ import org.springframework.tests.TestGroup;
import org.springframework.util.ClassUtils;
import org.springframework.util.StopWatch;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertArrayEquals;
@@ -93,9 +94,10 @@ public class DefaultConversionServiceTests {
assertEquals(null, conversionService.convert("", Character.class));
}
@Test(expected = ConversionFailedException.class)
@Test
public void testStringToCharacterInvalidString() {
conversionService.convert("invalid", Character.class);
assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() ->
conversionService.convert("invalid", Character.class));
}
@Test
@@ -130,9 +132,10 @@ public class DefaultConversionServiceTests {
assertEquals(null, conversionService.convert("", Boolean.class));
}
@Test(expected = ConversionFailedException.class)
@Test
public void testStringToBooleanInvalidString() {
conversionService.convert("invalid", Boolean.class);
assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() ->
conversionService.convert("invalid", Boolean.class));
}
@Test
@@ -331,9 +334,10 @@ public class DefaultConversionServiceTests {
assertEquals(Long.valueOf(1), conversionService.convert(1, Long.class));
}
@Test(expected = ConversionFailedException.class)
@Test
public void testNumberToNumberNotSupportedNumber() {
conversionService.convert(1, CustomNumber.class);
assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() ->
conversionService.convert(1, CustomNumber.class));
}
@Test
@@ -397,9 +401,10 @@ public class DefaultConversionServiceTests {
assertEquals("3", result.get(2));
}
@Test(expected = ConversionFailedException.class)
@Test
public void convertArrayToAbstractCollection() {
conversionService.convert(new String[]{"1", "2", "3"}, AbstractList.class);
assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() ->
conversionService.convert(new String[]{"1", "2", "3"}, AbstractList.class));
}
@Test
@@ -881,9 +886,10 @@ public class DefaultConversionServiceTests {
assertEquals(ZoneId.of("GMT+1"), conversionService.convert("GMT+1", ZoneId.class));
}
@Test(expected = ConverterNotFoundException.class)
@Test
public void convertObjectToObjectNoValueOfMethodOrConstructor() {
conversionService.convert(Long.valueOf(3), SSN.class);
assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() ->
conversionService.convert(Long.valueOf(3), SSN.class));
}
@Test

View File

@@ -40,6 +40,7 @@ import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
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;
@@ -236,22 +237,24 @@ public class CollectionToCollectionConverterTests {
assertSame(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources"))));
}
@Test(expected = ConverterNotFoundException.class)
@Test
public void elementTypesNotConvertible() throws Exception {
List<String> resources = new ArrayList<>();
resources.add(null);
resources.add(null);
TypeDescriptor sourceType = new TypeDescriptor(getClass().getField("strings"));
assertEquals(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources"))));
assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() ->
conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources"))));
}
@Test(expected = ConversionFailedException.class)
@Test
public void nothingInCommon() throws Exception {
List<Object> resources = new ArrayList<>();
resources.add(new ClassPathResource("test"));
resources.add(3);
TypeDescriptor sourceType = TypeDescriptor.forObject(resources);
assertEquals(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources"))));
assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() ->
conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources"))));
}
@Test

View File

@@ -51,6 +51,9 @@ import org.springframework.util.StringUtils;
import static java.util.Comparator.naturalOrder;
import static java.util.stream.Collectors.toList;
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.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertArrayEquals;
@@ -59,7 +62,6 @@ import static org.junit.Assert.assertFalse;
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 GenericConversionService}.
@@ -92,14 +94,16 @@ public class GenericConversionServiceTests {
assertTrue(conversionService.canConvert(boolean.class, Boolean.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void canConvertFromClassSourceTypeToNullTargetType() {
conversionService.canConvert(String.class, null);
assertThatIllegalArgumentException().isThrownBy(() ->
conversionService.canConvert(String.class, null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void canConvertFromTypeDescriptorSourceTypeToNullTargetType() {
conversionService.canConvert(TypeDescriptor.valueOf(String.class), null);
assertThatIllegalArgumentException().isThrownBy(() ->
conversionService.canConvert(TypeDescriptor.valueOf(String.class), null));
}
@Test
@@ -119,19 +123,22 @@ public class GenericConversionServiceTests {
assertEquals(null, conversionService.convert(null, Integer.class));
}
@Test(expected = ConversionFailedException.class)
@Test
public void convertNullSourcePrimitiveTarget() {
conversionService.convert(null, int.class);
assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() ->
conversionService.convert(null, int.class));
}
@Test(expected = ConversionFailedException.class)
@Test
public void convertNullSourcePrimitiveTargetTypeDescriptor() {
conversionService.convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(int.class));
assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() ->
conversionService.convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(int.class)));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void convertNotNullSourceNullSourceTypeDescriptor() {
conversionService.convert("3", null, TypeDescriptor.valueOf(int.class));
assertThatIllegalArgumentException().isThrownBy(() ->
conversionService.convert("3", null, TypeDescriptor.valueOf(int.class)));
}
@Test
@@ -140,14 +147,16 @@ public class GenericConversionServiceTests {
assertEquals(Boolean.FALSE, conversionService.convert(false, Boolean.class));
}
@Test(expected = ConverterNotFoundException.class)
@Test
public void converterNotFound() {
conversionService.convert("3", Integer.class);
assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() ->
conversionService.convert("3", Integer.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void addConverterNoSourceTargetClassInfoAvailable() {
conversionService.addConverter(new UntypedConverter());
assertThatIllegalArgumentException().isThrownBy(() ->
conversionService.addConverter(new UntypedConverter()));
}
@Test
@@ -165,25 +174,29 @@ public class GenericConversionServiceTests {
assertNull(conversionService.convert(null, Integer.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void convertToNullTargetClass() {
conversionService.convert("3", (Class<?>) null);
assertThatIllegalArgumentException().isThrownBy(() ->
conversionService.convert("3", (Class<?>) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void convertToNullTargetTypeDescriptor() {
conversionService.convert("3", TypeDescriptor.valueOf(String.class), null);
assertThatIllegalArgumentException().isThrownBy(() ->
conversionService.convert("3", TypeDescriptor.valueOf(String.class), null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void convertWrongSourceTypeDescriptor() {
conversionService.convert("3", TypeDescriptor.valueOf(Integer.class), TypeDescriptor.valueOf(Long.class));
assertThatIllegalArgumentException().isThrownBy(() ->
conversionService.convert("3", TypeDescriptor.valueOf(Integer.class), TypeDescriptor.valueOf(Long.class)));
}
@Test(expected = ConversionFailedException.class)
@Test
public void convertWrongTypeArgument() {
conversionService.addConverterFactory(new StringToNumberConverterFactory());
conversionService.convert("BOGUS", Integer.class);
assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() ->
conversionService.convert("BOGUS", Integer.class));
}
@Test
@@ -199,10 +212,11 @@ public class GenericConversionServiceTests {
}
// SPR-8718
@Test(expected = ConverterNotFoundException.class)
@Test
public void convertSuperTarget() {
conversionService.addConverter(new ColorConverter());
conversionService.convert("#000000", SystemColor.class);
assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() ->
conversionService.convert("#000000", SystemColor.class));
}
@Test
@@ -226,11 +240,12 @@ public class GenericConversionServiceTests {
assertEquals(3, three.intValue());
}
@Test(expected = ConverterNotFoundException.class)
@Test
public void genericConverterDelegatingBackToConversionServiceConverterNotFound() {
conversionService.addConverter(new ObjectToArrayConverter(conversionService));
assertFalse(conversionService.canConvert(String.class, Integer[].class));
conversionService.convert("3,4,5", Integer[].class);
assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() ->
conversionService.convert("3,4,5", Integer[].class));
}
@Test
@@ -445,14 +460,16 @@ public class GenericConversionServiceTests {
assertFalse(pair.hashCode() == pairOpposite.hashCode());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void canConvertIllegalArgumentNullTargetTypeFromClass() {
conversionService.canConvert(String.class, null);
assertThatIllegalArgumentException().isThrownBy(() ->
conversionService.canConvert(String.class, null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void canConvertIllegalArgumentNullTargetTypeFromTypeDescriptor() {
conversionService.canConvert(TypeDescriptor.valueOf(String.class), null);
assertThatIllegalArgumentException().isThrownBy(() ->
conversionService.canConvert(TypeDescriptor.valueOf(String.class), null));
}
@Test
@@ -500,13 +517,9 @@ public class GenericConversionServiceTests {
@Test
public void shouldNotSupportNullConvertibleTypesFromNonConditionalGenericConverter() {
GenericConverter converter = new NonConditionalGenericConverter();
try {
conversionService.addConverter(converter);
fail("Did not throw IllegalStateException");
}
catch (IllegalStateException ex) {
assertEquals("Only conditional converters may return null convertible types", ex.getMessage());
}
assertThatIllegalStateException().isThrownBy(() ->
conversionService.addConverter(converter))
.withMessage("Only conditional converters may return null convertible types");
}
@Test
@@ -606,13 +619,8 @@ public class GenericConversionServiceTests {
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection"))));
try {
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection")));
fail("Should have thrown ConverterNotFoundException");
}
catch (ConverterNotFoundException ex) {
// expected
}
assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() ->
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection"))));
}
@Test

View File

@@ -33,13 +33,13 @@ import org.springframework.core.convert.TypeDescriptor;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
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;
/**
* @author Keith Donald
@@ -152,13 +152,8 @@ public class MapToMapConverterTests {
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("collectionMapTarget"));
assertFalse(conversionService.canConvert(sourceType, targetType));
try {
conversionService.convert(map, sourceType, targetType);
fail("Should have failed");
}
catch (ConverterNotFoundException ex) {
// expected
}
assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() ->
conversionService.convert(map, sourceType, targetType));
conversionService.addConverter(new CollectionToCollectionConverter(conversionService));
conversionService.addConverterFactory(new StringToNumberConverterFactory());

View File

@@ -22,6 +22,8 @@ import org.junit.Test;
import org.springframework.mock.env.MockPropertySource;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
@@ -32,7 +34,6 @@ 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 Chris Beams
@@ -111,13 +112,9 @@ public class MutablePropertySourcesTests {
assertThat(sources.size(), equalTo(6));
String bogusPS = "bogus";
try {
sources.addAfter(bogusPS, new MockPropertySource("h"));
fail("expected non-existent PropertySource exception");
}
catch (IllegalArgumentException ex) {
assertTrue(ex.getMessage().contains("does not exist"));
}
assertThatIllegalArgumentException().isThrownBy(() ->
sources.addAfter(bogusPS, new MockPropertySource("h")))
.withMessageContaining("does not exist");
sources.addFirst(new MockPropertySource("a"));
assertThat(sources.size(), equalTo(7));
@@ -133,29 +130,17 @@ public class MutablePropertySourcesTests {
sources.replace("a-replaced", new MockPropertySource("a"));
try {
sources.replace(bogusPS, new MockPropertySource("bogus-replaced"));
fail("expected non-existent PropertySource exception");
}
catch (IllegalArgumentException ex) {
assertTrue(ex.getMessage().contains("does not exist"));
}
assertThatIllegalArgumentException().isThrownBy(() ->
sources.replace(bogusPS, new MockPropertySource("bogus-replaced")))
.withMessageContaining("does not exist");
try {
sources.addBefore("b", new MockPropertySource("b"));
fail("expected exception");
}
catch (IllegalArgumentException ex) {
assertTrue(ex.getMessage().contains("cannot be added relative to itself"));
}
assertThatIllegalArgumentException().isThrownBy(() ->
sources.addBefore("b", new MockPropertySource("b")))
.withMessageContaining("cannot be added relative to itself");
try {
sources.addAfter("b", new MockPropertySource("b"));
fail("expected exception");
}
catch (IllegalArgumentException ex) {
assertTrue(ex.getMessage().contains("cannot be added relative to itself"));
}
assertThatIllegalArgumentException().isThrownBy(() ->
sources.addAfter("b", new MockPropertySource("b")))
.withMessageContaining("cannot be added relative to itself");
}
@Test
@@ -173,13 +158,8 @@ public class MutablePropertySourcesTests {
assertTrue(it.hasNext());
assertEquals("test", it.next().getName());
try {
it.remove();
fail("Should have thrown UnsupportedOperationException");
}
catch (UnsupportedOperationException ex) {
// expected
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(
it::remove);
assertFalse(it.hasNext());
}

View File

@@ -29,7 +29,6 @@ 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;
/**
* Tests for {@link Profiles}.
@@ -296,13 +295,9 @@ public class ProfilesTests {
}
private void assertMalformed(Supplier<Profiles> supplier) {
try {
supplier.get();
fail("Not malformed");
}
catch (IllegalArgumentException ex) {
assertTrue(ex.getMessage().contains("Malformed"));
}
assertThatIllegalArgumentException().isThrownBy(
supplier::get)
.withMessageContaining("Malformed");
}
private static Predicate<String> activeProfiles(String... profiles) {

View File

@@ -26,13 +26,15 @@ import org.junit.Test;
import org.springframework.core.convert.ConverterNotFoundException;
import org.springframework.mock.env.MockPropertySource;
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.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Chris Beams
@@ -117,13 +119,8 @@ public class PropertySourcesPropertyResolverTests {
class TestType { }
try {
propertyResolver.getProperty("foo", TestType.class);
fail("Expected ConverterNotFoundException due to non-convertible types");
}
catch (ConverterNotFoundException ex) {
// expected
}
assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() ->
propertyResolver.getProperty("foo", TestType.class));
}
@Test
@@ -177,13 +174,8 @@ public class PropertySourcesPropertyResolverTests {
testProperties.put("exists", "xyz");
assertThat(propertyResolver.getRequiredProperty("exists"), is("xyz"));
try {
propertyResolver.getRequiredProperty("bogus");
fail("expected IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
propertyResolver.getRequiredProperty("bogus"));
}
@Test
@@ -191,13 +183,8 @@ public class PropertySourcesPropertyResolverTests {
testProperties.put("exists", "abc,123");
assertThat(propertyResolver.getRequiredProperty("exists", String[].class), equalTo(new String[] { "abc", "123" }));
try {
propertyResolver.getRequiredProperty("bogus", String[].class);
fail("expected IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
propertyResolver.getRequiredProperty("bogus", String[].class));
}
@Test
@@ -226,9 +213,10 @@ public class PropertySourcesPropertyResolverTests {
equalTo("Replace this value plus defaultValue"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void resolvePlaceholders_withNullInput() {
new PropertySourcesPropertyResolver(new MutablePropertySources()).resolvePlaceholders(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new PropertySourcesPropertyResolver(new MutablePropertySources()).resolvePlaceholders(null));
}
@Test
@@ -239,12 +227,13 @@ public class PropertySourcesPropertyResolverTests {
assertThat(resolver.resolveRequiredPlaceholders("Replace this ${key}"), equalTo("Replace this value"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void resolveRequiredPlaceholders_withUnresolvable() {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MockPropertySource().withProperty("key", "value"));
PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources);
resolver.resolveRequiredPlaceholders("Replace this ${key} plus ${unknown}");
assertThatIllegalArgumentException().isThrownBy(() ->
resolver.resolveRequiredPlaceholders("Replace this ${key} plus ${unknown}"));
}
@Test
@@ -256,9 +245,10 @@ public class PropertySourcesPropertyResolverTests {
equalTo("Replace this value plus defaultValue"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void resolveRequiredPlaceholders_withNullInput() {
new PropertySourcesPropertyResolver(new MutablePropertySources()).resolveRequiredPlaceholders(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new PropertySourcesPropertyResolver(new MutablePropertySources()).resolveRequiredPlaceholders(null));
}
@Test
@@ -270,27 +260,17 @@ public class PropertySourcesPropertyResolverTests {
propertyResolver.setRequiredProperties("foo", "bar");
// neither foo nor bar properties are present -> validating should throw
try {
propertyResolver.validateRequiredProperties();
fail("expected validation exception");
}
catch (MissingRequiredPropertiesException ex) {
assertThat(ex.getMessage(), equalTo(
"The following properties were declared as required " +
"but could not be resolved: [foo, bar]"));
}
assertThatExceptionOfType(MissingRequiredPropertiesException.class).isThrownBy(
propertyResolver::validateRequiredProperties)
.withMessage("The following properties were declared as required " +
"but could not be resolved: [foo, bar]");
// add foo property -> validation should fail only on missing 'bar' property
testProperties.put("foo", "fooValue");
try {
propertyResolver.validateRequiredProperties();
fail("expected validation exception");
}
catch (MissingRequiredPropertiesException ex) {
assertThat(ex.getMessage(), equalTo(
"The following properties were declared as required " +
"but could not be resolved: [bar]"));
}
assertThatExceptionOfType(MissingRequiredPropertiesException.class).isThrownBy(
propertyResolver::validateRequiredProperties)
.withMessage("The following properties were declared as required " +
"but could not be resolved: [bar]");
// add bar property -> validation should pass, even with an empty string value
testProperties.put("bar", "");

View File

@@ -21,6 +21,8 @@ import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
@@ -62,28 +64,32 @@ public class SimpleCommandLineParserTests {
assertThat(args.getOptionValues("o3"), nullValue());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void withEmptyOptionText() {
SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser();
parser.parse("--");
assertThatIllegalArgumentException().isThrownBy(() ->
parser.parse("--"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void withEmptyOptionName() {
SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser();
parser.parse("--=v1");
assertThatIllegalArgumentException().isThrownBy(() ->
parser.parse("--=v1"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void withEmptyOptionValue() {
SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser();
parser.parse("--o1=");
assertThatIllegalArgumentException().isThrownBy(() ->
parser.parse("--o1="));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void withEmptyOptionNameAndEmptyOptionValue() {
SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser();
parser.parse("--=");
assertThatIllegalArgumentException().isThrownBy(() ->
parser.parse("--="));
}
@Test
@@ -99,16 +105,18 @@ public class SimpleCommandLineParserTests {
assertThat(nonOptions.size(), equalTo(2));
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void assertOptionNamesIsUnmodifiable() {
CommandLineArgs args = new SimpleCommandLineArgsParser().parse();
args.getOptionNames().add("bogus");
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
args.getOptionNames().add("bogus"));
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void assertNonOptionArgsIsUnmodifiable() {
CommandLineArgs args = new SimpleCommandLineArgsParser().parse();
args.getNonOptionArgs().add("foo");
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
args.getNonOptionArgs().add("foo"));
}
}

View File

@@ -28,6 +28,7 @@ import org.junit.Test;
import org.springframework.core.SpringProperties;
import org.springframework.mock.env.MockPropertySource;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.equalTo;
@@ -40,7 +41,6 @@ import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.core.env.AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME;
import static org.springframework.core.env.AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME;
import static org.springframework.core.env.AbstractEnvironment.RESERVED_DEFAULT_PROFILE_NAME;
@@ -144,44 +144,52 @@ public class StandardEnvironmentTests {
assertThat(activeProfiles.length, is(2));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setActiveProfiles_withNullProfileArray() {
environment.setActiveProfiles((String[]) null);
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setActiveProfiles((String[]) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setActiveProfiles_withNullProfile() {
environment.setActiveProfiles((String) null);
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setActiveProfiles((String) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setActiveProfiles_withEmptyProfile() {
environment.setActiveProfiles("");
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setActiveProfiles(""));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setActiveProfiles_withNotOperator() {
environment.setActiveProfiles("p1", "!p2");
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setActiveProfiles("p1", "!p2"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setDefaultProfiles_withNullProfileArray() {
environment.setDefaultProfiles((String[]) null);
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setDefaultProfiles((String[]) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setDefaultProfiles_withNullProfile() {
environment.setDefaultProfiles((String) null);
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setDefaultProfiles((String) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setDefaultProfiles_withEmptyProfile() {
environment.setDefaultProfiles("");
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setDefaultProfiles(""));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setDefaultProfiles_withNotOperator() {
environment.setDefaultProfiles("d1", "!d2");
assertThatIllegalArgumentException().isThrownBy(() ->
environment.setDefaultProfiles("d1", "!d2"));
}
@Test
@@ -219,11 +227,12 @@ public class StandardEnvironmentTests {
System.getProperties().remove(DEFAULT_PROFILES_PROPERTY_NAME);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void defaultProfileWithCircularPlaceholder() {
System.setProperty(DEFAULT_PROFILES_PROPERTY_NAME, "${spring.profiles.default}");
try {
environment.getDefaultProfiles();
assertThatIllegalArgumentException().isThrownBy(() ->
environment.getDefaultProfiles());
}
finally {
System.getProperties().remove(DEFAULT_PROFILES_PROPERTY_NAME);
@@ -278,24 +287,28 @@ public class StandardEnvironmentTests {
assertThat(Arrays.asList(environment.getDefaultProfiles()), hasItems("pd2", "pd3"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void acceptsProfiles_withEmptyArgumentList() {
environment.acceptsProfiles();
assertThatIllegalArgumentException().isThrownBy(
environment::acceptsProfiles);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void acceptsProfiles_withNullArgumentList() {
environment.acceptsProfiles((String[]) null);
assertThatIllegalArgumentException().isThrownBy(() ->
environment.acceptsProfiles((String[]) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void acceptsProfiles_withNullArgument() {
environment.acceptsProfiles((String) null);
assertThatIllegalArgumentException().isThrownBy(() ->
environment.acceptsProfiles((String) null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void acceptsProfiles_withEmptyArgument() {
environment.acceptsProfiles("");
assertThatIllegalArgumentException().isThrownBy(() ->
environment.acceptsProfiles(""));
}
@Test
@@ -335,9 +348,10 @@ public class StandardEnvironmentTests {
assertThat(environment.acceptsProfiles("!p1"), is(false));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void acceptsProfiles_withInvalidNotOperator() {
environment.acceptsProfiles("p1", "!");
assertThatIllegalArgumentException().isThrownBy(() ->
environment.acceptsProfiles("p1", "!"));
}
@Test
@@ -364,14 +378,9 @@ public class StandardEnvironmentTests {
env.addActiveProfile("validProfile"); // succeeds
try {
env.addActiveProfile("invalid-profile");
fail("expected validation exception");
}
catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(),
equalTo("Invalid profile [invalid-profile]: must not contain dash character"));
}
assertThatIllegalArgumentException().isThrownBy(() ->
env.addActiveProfile("invalid-profile"))
.withMessage("Invalid profile [invalid-profile]: must not contain dash character");
}
@Test
@@ -454,13 +463,8 @@ public class StandardEnvironmentTests {
// the user that under these very special conditions (non-object key +
// SecurityManager that disallows access to system properties), they
// cannot do what they're attempting.
try {
systemProperties.get(NON_STRING_PROPERTY_NAME);
fail("Expected IllegalArgumentException when searching with non-string key against ReadOnlySystemAttributesMap");
}
catch (IllegalArgumentException ex) {
// expected
}
assertThatIllegalArgumentException().as("searching with non-string key against ReadOnlySystemAttributesMap").isThrownBy(() ->
systemProperties.get(NON_STRING_PROPERTY_NAME));
}
System.setSecurityManager(oldSecurityManager);

View File

@@ -17,19 +17,15 @@
package org.springframework.core.io;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.instanceOf;
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;
/**
* Unit tests that serve as regression tests for the bugs described in SPR-6888
@@ -136,14 +132,9 @@ public class ClassPathResourceTests {
}
private void assertExceptionContainsFullyQualifiedPath(ClassPathResource resource) {
try {
resource.getInputStream();
fail("FileNotFoundException expected for resource: " + resource);
}
catch (IOException ex) {
assertThat(ex, instanceOf(FileNotFoundException.class));
assertThat(ex.getMessage(), containsString(FQ_RESOURCE_PATH));
}
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(
resource::getInputStream)
.withMessageContaining(FQ_RESOURCE_PATH);
}
}

View File

@@ -22,6 +22,7 @@ import org.junit.Test;
import org.springframework.core.env.StandardEnvironment;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@@ -44,9 +45,10 @@ public class ResourceEditorTests {
assertTrue(resource.exists());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void ctorWithNullCtorArgs() throws Exception {
new ResourceEditor(null, null);
assertThatIllegalArgumentException().isThrownBy(() ->
new ResourceEditor(null, null));
}
@Test
@@ -77,14 +79,15 @@ public class ResourceEditorTests {
}
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testStrictSystemPropertyReplacement() {
PropertyEditor editor = new ResourceEditor(new DefaultResourceLoader(), new StandardEnvironment(), false);
System.setProperty("test.prop", "foo");
try {
editor.setAsText("${test.prop}-${bar}");
Resource resolved = (Resource) editor.getValue();
assertEquals("foo-${bar}", resolved.getFilename());
assertThatIllegalArgumentException().isThrownBy(() -> {
editor.setAsText("${test.prop}-${bar}");
editor.getValue();
});
}
finally {
System.getProperties().remove("test.prop");

View File

@@ -32,13 +32,13 @@ import org.junit.Test;
import org.springframework.util.FileCopyUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
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 various {@link Resource} implementations.
@@ -197,20 +197,10 @@ public class ResourceTests {
Resource relative4 = resource.createRelative("X.class");
assertFalse(relative4.exists());
assertFalse(relative4.isReadable());
try {
relative4.contentLength();
fail("Should have thrown FileNotFoundException");
}
catch (FileNotFoundException ex) {
// expected
}
try {
relative4.lastModified();
fail("Should have thrown FileNotFoundException");
}
catch (FileNotFoundException ex) {
// expected
}
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(
relative4::contentLength);
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(
relative4::lastModified);
}
@Test
@@ -255,27 +245,15 @@ public class ResourceTests {
}
};
try {
resource.getURL();
fail("FileNotFoundException should have been thrown");
}
catch (FileNotFoundException ex) {
assertTrue(ex.getMessage().contains(name));
}
try {
resource.getFile();
fail("FileNotFoundException should have been thrown");
}
catch (FileNotFoundException ex) {
assertTrue(ex.getMessage().contains(name));
}
try {
resource.createRelative("/testing");
fail("FileNotFoundException should have been thrown");
}
catch (FileNotFoundException ex) {
assertTrue(ex.getMessage().contains(name));
}
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(
resource::getURL)
.withMessageContaining(name);
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(
resource::getFile)
.withMessageContaining(name);
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() ->
resource.createRelative("/testing"))
.withMessageContaining(name);
assertThat(resource.getFilename(), nullValue());
}
@@ -313,24 +291,28 @@ public class ResourceTests {
}
}
@Test(expected = FileNotFoundException.class)
@Test
public void testInputStreamNotFoundOnFileSystemResource() throws IOException {
new FileSystemResource(getClass().getResource("Resource.class").getFile()).createRelative("X").getInputStream();
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() ->
new FileSystemResource(getClass().getResource("Resource.class").getFile()).createRelative("X").getInputStream());
}
@Test(expected = FileNotFoundException.class)
@Test
public void testReadableChannelNotFoundOnFileSystemResource() throws IOException {
new FileSystemResource(getClass().getResource("Resource.class").getFile()).createRelative("X").readableChannel();
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() ->
new FileSystemResource(getClass().getResource("Resource.class").getFile()).createRelative("X").readableChannel());
}
@Test(expected = FileNotFoundException.class)
@Test
public void testInputStreamNotFoundOnClassPathResource() throws IOException {
new ClassPathResource("Resource.class", getClass()).createRelative("X").getInputStream();
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() ->
new ClassPathResource("Resource.class", getClass()).createRelative("X").getInputStream());
}
@Test(expected = FileNotFoundException.class)
@Test
public void testReadableChannelNotFoundOnClassPathResource() throws IOException {
new ClassPathResource("Resource.class", getClass()).createRelative("X").readableChannel();
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() ->
new ClassPathResource("Resource.class", getClass()).createRelative("X").readableChannel());
}
}

View File

@@ -25,10 +25,11 @@ import java.util.Arrays;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
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.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Arjen Poutsma
@@ -80,10 +81,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
public void readPositionSmallerThanZero() {
DataBuffer buffer = createDataBuffer(1);
try {
buffer.readPosition(-1);
fail("IndexOutOfBoundsException expected");
}
catch (IndexOutOfBoundsException ignored) {
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() ->
buffer.readPosition(-1));
}
finally {
release(buffer);
@@ -94,10 +93,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
public void readPositionGreaterThanWritePosition() {
DataBuffer buffer = createDataBuffer(1);
try {
buffer.readPosition(1);
fail("IndexOutOfBoundsException expected");
}
catch (IndexOutOfBoundsException ignored) {
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() ->
buffer.readPosition(1));
}
finally {
release(buffer);
@@ -110,11 +107,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
try {
buffer.write((byte) 'a');
buffer.read();
buffer.writePosition(0);
fail("IndexOutOfBoundsException expected");
}
catch (IndexOutOfBoundsException ignored) {
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() ->
buffer.writePosition(0));
}
finally {
release(buffer);
@@ -125,10 +119,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
public void writePositionGreaterThanCapacity() {
DataBuffer buffer = createDataBuffer(1);
try {
buffer.writePosition(2);
fail("IndexOutOfBoundsException expected");
}
catch (IndexOutOfBoundsException ignored) {
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() ->
buffer.writePosition(2));
}
finally {
release(buffer);
@@ -158,10 +150,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
public void writeNullString() {
DataBuffer buffer = createDataBuffer(1);
try {
buffer.write(null, StandardCharsets.UTF_8);
fail("IllegalArgumentException expected");
}
catch (IllegalArgumentException exc) {
assertThatIllegalArgumentException().isThrownBy(() ->
buffer.write(null, StandardCharsets.UTF_8));
}
finally {
release(buffer);
@@ -172,10 +162,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
public void writeNullCharset() {
DataBuffer buffer = createDataBuffer(1);
try {
buffer.write("test", null);
fail("IllegalArgumentException expected");
}
catch (IllegalArgumentException exc) {
assertThatIllegalArgumentException().isThrownBy(() ->
buffer.write("test", null));
}
finally {
release(buffer);
@@ -369,10 +357,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
public void capacityLessThanZero() {
DataBuffer buffer = createDataBuffer(1);
try {
buffer.capacity(-1);
fail("IllegalArgumentException expected");
}
catch (IllegalArgumentException ignored) {
assertThatIllegalArgumentException().isThrownBy(() ->
buffer.capacity(-1));
}
finally {
release(buffer);
@@ -558,12 +544,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
DataBuffer slice = buffer.slice(1, 2);
assertEquals(2, slice.readableByteCount());
try {
slice.write((byte) 0);
fail("Exception expected");
}
catch (Exception ignored) {
}
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
slice.write((byte) 0));
buffer.write((byte) 'c');
assertEquals(3, buffer.readableByteCount());
@@ -589,12 +571,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
DataBuffer slice = buffer.retainedSlice(1, 2);
assertEquals(2, slice.readableByteCount());
try {
slice.write((byte) 0);
fail("Exception expected");
}
catch (Exception ignored) {
}
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
slice.write((byte) 0));
buffer.write((byte) 'c');
assertEquals(3, buffer.readableByteCount());
@@ -651,19 +629,11 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
assertEquals('a', buffer.getByte(0));
assertEquals('b', buffer.getByte(1));
assertEquals('c', buffer.getByte(2));
try {
buffer.getByte(-1);
fail("IndexOutOfBoundsException expected");
}
catch (IndexOutOfBoundsException ignored) {
}
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() ->
buffer.getByte(-1));
try {
buffer.getByte(3);
fail("IndexOutOfBoundsException expected");
}
catch (IndexOutOfBoundsException ignored) {
}
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() ->
buffer.getByte(3));
release(buffer);
}

View File

@@ -49,7 +49,6 @@ import org.springframework.core.io.Resource;
import org.springframework.core.io.buffer.support.DataBufferTestUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.isA;
@@ -489,17 +488,17 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
DataBufferUtils.write(sourceFlux, channel)
.subscribe(DataBufferUtils.releaseConsumer(),
throwable -> fail(throwable.getMessage()),
throwable -> {
throw new AssertionError(throwable.getMessage(), throwable);
},
() -> {
try {
String expected = String.join("", Files.readAllLines(source));
String result = String.join("", Files.readAllLines(destination));
assertEquals(expected, result);
}
catch (IOException e) {
fail(e.getMessage());
throw new AssertionError(e.getMessage(), e);
}
finally {
DataBufferUtils.closeChannel(channel);
@@ -523,7 +522,9 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
DataBufferUtils.write(sourceFlux, channel)
.subscribe(DataBufferUtils::release,
throwable -> fail(throwable.getMessage()),
throwable -> {
throw new AssertionError(throwable.getMessage(), throwable);
},
() -> {
try {
String expected = String.join("", Files.readAllLines(source));
@@ -534,7 +535,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
}
catch (IOException e) {
fail(e.getMessage());
throw new AssertionError(e.getMessage(), e);
}
finally {
DataBufferUtils.closeChannel(channel);

View File

@@ -18,7 +18,7 @@ package org.springframework.core.io.buffer;
import org.junit.Test;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.core.io.buffer.DataBufferUtils.release;
/**
@@ -33,11 +33,8 @@ public class LeakAwareDataBufferFactoryTests {
public void leak() {
DataBuffer dataBuffer = this.bufferFactory.allocateBuffer();
try {
this.bufferFactory.checkForLeaks();
fail("AssertionError expected");
}
catch (AssertionError expected) {
// ignore
assertThatExceptionOfType(AssertionError.class).isThrownBy(
this.bufferFactory::checkForLeaks);
}
finally {
release(dataBuffer);

View File

@@ -22,6 +22,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -60,13 +61,14 @@ public class PooledDataBufferTests {
assertTrue(result);
}
@Test(expected = IllegalStateException.class)
@Test
public void tooManyReleases() {
PooledDataBuffer buffer = createDataBuffer(1);
buffer.write((byte) 'a');
buffer.release();
buffer.release();
assertThatIllegalStateException().isThrownBy(
buffer::release);
}

View File

@@ -28,6 +28,7 @@ import org.junit.Test;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -58,9 +59,10 @@ public class PathMatchingResourcePatternResolverTests {
private PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
@Test(expected = FileNotFoundException.class)
@Test
public void invalidPrefixWithPatternElementInIt() throws IOException {
resolver.getResources("xx**:**/*.xy");
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() ->
resolver.getResources("xx**:**/*.xy"));
}
@Test

View File

@@ -23,6 +23,7 @@ import org.junit.Test;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.Resource;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@@ -69,16 +70,15 @@ public class ResourceArrayPropertyEditorTests {
}
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testStrictSystemPropertyReplacement() {
PropertyEditor editor = new ResourceArrayPropertyEditor(
new PathMatchingResourcePatternResolver(), new StandardEnvironment(),
false);
System.setProperty("test.prop", "foo");
try {
editor.setAsText("${test.prop}-${bar}");
Resource[] resources = (Resource[]) editor.getValue();
assertEquals("foo-${bar}", resources[0].getFilename());
assertThatIllegalArgumentException().isThrownBy(() ->
editor.setAsText("${test.prop}-${bar}"));
}
finally {
System.getProperties().remove("test.prop");

View File

@@ -20,6 +20,7 @@ import org.junit.Test;
import org.springframework.core.io.Resource;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@@ -29,19 +30,22 @@ import static org.mockito.Mockito.mock;
*/
public class ResourceRegionTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void shouldThrowExceptionWithNullResource() {
new ResourceRegion(null, 0, 1);
assertThatIllegalArgumentException().isThrownBy(() ->
new ResourceRegion(null, 0, 1));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void shouldThrowExceptionForNegativePosition() {
new ResourceRegion(mock(Resource.class), -1, 1);
assertThatIllegalArgumentException().isThrownBy(() ->
new ResourceRegion(mock(Resource.class), -1, 1));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void shouldThrowExceptionForNegativeCount() {
new ResourceRegion(mock(Resource.class), 0, -1);
assertThatIllegalArgumentException().isThrownBy(() ->
new ResourceRegion(mock(Resource.class), 0, -1));
}
}

View File

@@ -25,10 +25,8 @@ import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializationFailedException;
import org.springframework.core.serializer.support.SerializingConverter;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Gary Russell
@@ -48,33 +46,24 @@ public class SerializationConverterTests {
@Test
public void nonSerializableObject() {
SerializingConverter toBytes = new SerializingConverter();
try {
toBytes.convert(new Object());
fail("Expected IllegalArgumentException");
}
catch (SerializationFailedException e) {
assertNotNull(e.getCause());
assertTrue(e.getCause() instanceof IllegalArgumentException);
}
assertThatExceptionOfType(SerializationFailedException.class).isThrownBy(() ->
toBytes.convert(new Object()))
.withCauseInstanceOf(IllegalArgumentException.class);
}
@Test
public void nonSerializableField() {
SerializingConverter toBytes = new SerializingConverter();
try {
toBytes.convert(new UnSerializable());
fail("Expected SerializationFailureException");
}
catch (SerializationFailedException e) {
assertNotNull(e.getCause());
assertTrue(e.getCause() instanceof NotSerializableException);
}
assertThatExceptionOfType(SerializationFailedException.class).isThrownBy(() ->
toBytes.convert(new UnSerializable()))
.withCauseInstanceOf(NotSerializableException.class);
}
@Test(expected = SerializationFailedException.class)
@Test
public void deserializationFailure() {
DeserializingConverter fromBytes = new DeserializingConverter();
fromBytes.convert("Junk".getBytes());
assertThatExceptionOfType(SerializationFailedException.class).isThrownBy(() ->
fromBytes.convert("Junk".getBytes()));
}

View File

@@ -23,10 +23,12 @@ import java.util.NoSuchElementException;
import org.junit.Test;
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;
/**
@@ -41,13 +43,8 @@ public class CompositeIteratorTests {
public void testNoIterators() {
CompositeIterator<String> it = new CompositeIterator<>();
assertFalse(it.hasNext());
try {
it.next();
fail();
}
catch (NoSuchElementException ex) {
// expected
}
assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(
it::next);
}
@Test
@@ -59,13 +56,8 @@ public class CompositeIteratorTests {
assertEquals(String.valueOf(i), it.next());
}
assertFalse(it.hasNext());
try {
it.next();
fail();
}
catch (NoSuchElementException ex) {
// expected
}
assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(
it::next);
}
@Test
@@ -79,13 +71,9 @@ public class CompositeIteratorTests {
assertEquals(String.valueOf(i), it.next());
}
assertFalse(it.hasNext());
try {
it.next();
fail();
}
catch (NoSuchElementException ex) {
// expected
}
assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(
it::next);
}
@Test
@@ -94,23 +82,13 @@ public class CompositeIteratorTests {
CompositeIterator<String> it = new CompositeIterator<>();
it.add(list.iterator());
it.hasNext();
try {
it.add(list.iterator());
fail();
}
catch (IllegalStateException ex) {
// expected
}
it = new CompositeIterator<>();
it.add(list.iterator());
it.next();
try {
it.add(list.iterator());
fail();
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
it.add(list.iterator()));
CompositeIterator<String> it2 = new CompositeIterator<>();
it2.add(list.iterator());
it2.next();
assertThatIllegalStateException().isThrownBy(() ->
it2.add(list.iterator()));
}
@Test
@@ -120,13 +98,8 @@ public class CompositeIteratorTests {
CompositeIterator<String> it = new CompositeIterator<>();
it.add(iterator);
it.add(list.iterator());
try {
it.add(iterator);
fail();
}
catch (IllegalArgumentException ex) {
// expected
}
assertThatIllegalArgumentException().isThrownBy(() ->
it.add(iterator));
}
}

View File

@@ -24,6 +24,8 @@ import java.nio.charset.StandardCharsets;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIOException;
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.assertNotNull;
@@ -84,10 +86,11 @@ public class FastByteArrayOutputStreamTests {
assertByteArrayEqualsString(this.os);
}
@Test(expected = IOException.class)
@Test
public void close() throws Exception {
this.os.close();
this.os.write(this.helloBytes);
assertThatIOException().isThrownBy(() ->
this.os.write(this.helloBytes));
}
@Test
@@ -107,10 +110,11 @@ public class FastByteArrayOutputStreamTests {
assertArrayEquals(baos.toByteArray(), this.helloBytes);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void failResize() throws Exception {
this.os.write(this.helloBytes);
this.os.resize(5);
assertThatIllegalArgumentException().isThrownBy(() ->
this.os.resize(5));
}
@Test

View File

@@ -28,6 +28,8 @@ import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import static java.util.Collections.singletonMap;
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;
@@ -44,34 +46,40 @@ import static org.junit.Assert.assertTrue;
*/
public class MimeTypeTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void slashInSubtype() {
new MimeType("text", "/");
assertThatIllegalArgumentException().isThrownBy(() ->
new MimeType("text", "/"));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void valueOfNoSubtype() {
MimeType.valueOf("audio");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeType.valueOf("audio"));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void valueOfNoSubtypeSlash() {
MimeType.valueOf("audio/");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeType.valueOf("audio/"));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void valueOfIllegalType() {
MimeType.valueOf("audio(/basic");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeType.valueOf("audio(/basic"));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void valueOfIllegalSubtype() {
MimeType.valueOf("audio/basic)");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeType.valueOf("audio/basic)"));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void valueOfIllegalCharset() {
MimeType.valueOf("text/html; charset=foo-bar");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeType.valueOf("text/html; charset=foo-bar"));
}
@Test
@@ -185,59 +193,70 @@ public class MimeTypeTests {
assertEquals("Invalid subtype", "*", mimeType.getSubtype());
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void parseMimeTypeNoSubtype() {
MimeTypeUtils.parseMimeType("audio");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeTypeUtils.parseMimeType("audio"));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void parseMimeTypeNoSubtypeSlash() {
MimeTypeUtils.parseMimeType("audio/");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeTypeUtils.parseMimeType("audio/"));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void parseMimeTypeTypeRange() {
MimeTypeUtils.parseMimeType("*/json");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeTypeUtils.parseMimeType("*/json"));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void parseMimeTypeIllegalType() {
MimeTypeUtils.parseMimeType("audio(/basic");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeTypeUtils.parseMimeType("audio(/basic"));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void parseMimeTypeIllegalSubtype() {
MimeTypeUtils.parseMimeType("audio/basic)");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeTypeUtils.parseMimeType("audio/basic)"));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void parseMimeTypeMissingTypeAndSubtype() {
MimeTypeUtils.parseMimeType(" ;a=b");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeTypeUtils.parseMimeType(" ;a=b"));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void parseMimeTypeEmptyParameterAttribute() {
MimeTypeUtils.parseMimeType("audio/*;=value");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeTypeUtils.parseMimeType("audio/*;=value"));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void parseMimeTypeEmptyParameterValue() {
MimeTypeUtils.parseMimeType("audio/*;attr=");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeTypeUtils.parseMimeType("audio/*;attr="));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void parseMimeTypeIllegalParameterAttribute() {
MimeTypeUtils.parseMimeType("audio/*;attr<=value");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeTypeUtils.parseMimeType("audio/*;attr<=value"));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void parseMimeTypeIllegalParameterValue() {
MimeTypeUtils.parseMimeType("audio/*;attr=v>alue");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeTypeUtils.parseMimeType("audio/*;attr=v>alue"));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void parseMimeTypeIllegalCharset() {
MimeTypeUtils.parseMimeType("text/html; charset=foo-bar");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeTypeUtils.parseMimeType("text/html; charset=foo-bar"));
}
@Test // SPR-8917
@@ -264,9 +283,10 @@ public class MimeTypeTests {
assertEquals("\" bar \"", mimeType.getParameter("foo"));
}
@Test(expected = InvalidMimeTypeException.class)
@Test
public void parseMimeTypeIllegalQuotedParameterValue() {
MimeTypeUtils.parseMimeType("audio/*;attr=\"");
assertThatExceptionOfType(InvalidMimeTypeException.class).isThrownBy(() ->
MimeTypeUtils.parseMimeType("audio/*;attr=\""));
}
@Test

View File

@@ -23,9 +23,8 @@ import java.util.Locale;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@@ -204,26 +203,14 @@ public class NumberUtilsTests {
String aLong = "" + Long.MAX_VALUE;
String aDouble = "" + Double.MAX_VALUE;
try {
NumberUtils.parseNumber(aLong, Byte.class);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Byte.class));
try {
NumberUtils.parseNumber(aLong, Short.class);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Short.class));
try {
NumberUtils.parseNumber(aLong, Integer.class);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Integer.class));
assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class));
assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class));
@@ -234,26 +221,14 @@ public class NumberUtilsTests {
String aLong = "" + Long.MIN_VALUE;
String aDouble = "" + Double.MIN_VALUE;
try {
NumberUtils.parseNumber(aLong, Byte.class);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Byte.class));
try {
NumberUtils.parseNumber(aLong, Short.class);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Short.class));
try {
NumberUtils.parseNumber(aLong, Integer.class);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Integer.class));
assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.parseNumber(aLong, Long.class));
assertEquals(Double.valueOf(Double.MIN_VALUE), NumberUtils.parseNumber(aDouble, Double.class));
@@ -265,26 +240,14 @@ public class NumberUtilsTests {
String aLong = "" + Long.MAX_VALUE;
String aDouble = "" + Double.MAX_VALUE;
try {
NumberUtils.parseNumber(aLong, Byte.class, nf);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Byte.class, nf));
try {
NumberUtils.parseNumber(aLong, Short.class, nf);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Short.class, nf));
try {
NumberUtils.parseNumber(aLong, Integer.class, nf);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Integer.class, nf));
assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf));
assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf));
@@ -296,26 +259,14 @@ public class NumberUtilsTests {
String aLong = "" + Long.MIN_VALUE;
String aDouble = "" + Double.MIN_VALUE;
try {
NumberUtils.parseNumber(aLong, Byte.class, nf);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Byte.class, nf));
try {
NumberUtils.parseNumber(aLong, Short.class, nf);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Short.class, nf));
try {
NumberUtils.parseNumber(aLong, Integer.class, nf);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Integer.class, nf));
assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf));
assertEquals(Double.valueOf(Double.MIN_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf));
@@ -451,15 +402,10 @@ public class NumberUtilsTests {
}
private void assertToNumberOverflow(Number number, Class<? extends Number> targetClass) {
String msg = "Expected exception due to overflow: from=" + number + ", toClass=" + targetClass;
try {
NumberUtils.convertNumberToTargetClass(number, targetClass);
fail(msg);
}
catch (IllegalArgumentException expected) {
assertTrue(msg + ", with \"overflow\" in message but got message=" + expected.getMessage(),
expected.getMessage().endsWith("overflow"));
}
String msg = "overflow: from=" + number + ", toClass=" + targetClass;
assertThatIllegalArgumentException().as(msg).isThrownBy(() ->
NumberUtils.convertNumberToTargetClass(number, targetClass))
.withMessageEndingWith("overflow");
}
}

View File

@@ -20,6 +20,7 @@ import java.util.Properties;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
/**
@@ -104,14 +105,15 @@ public class PropertyPlaceholderHelperTests {
assertEquals("foo=bar,bar=${bar}", this.helper.replacePlaceholders(text, props));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testUnresolvedPlaceholderAsError() {
String text = "foo=${foo},bar=${bar}";
Properties props = new Properties();
props.setProperty("foo", "bar");
PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${", "}", null, false);
assertEquals("foo=bar,bar=${bar}", helper.replacePlaceholders(text, props));
assertThatIllegalArgumentException().isThrownBy(() ->
helper.replacePlaceholders(text, props));
}
}

View File

@@ -32,6 +32,7 @@ import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup;
import org.springframework.tests.sample.objects.TestObject;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.sameInstance;
@@ -119,25 +120,28 @@ public class ReflectionUtilsTests {
assertFalse(ReflectionUtils.declaresException(illegalExMethod, Exception.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void copySrcToDestinationOfIncorrectClass() {
TestObject src = new TestObject();
String dest = new String();
ReflectionUtils.shallowCopyFieldState(src, dest);
assertThatIllegalArgumentException().isThrownBy(() ->
ReflectionUtils.shallowCopyFieldState(src, dest));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullSrc() {
TestObject src = null;
String dest = new String();
ReflectionUtils.shallowCopyFieldState(src, dest);
assertThatIllegalArgumentException().isThrownBy(() ->
ReflectionUtils.shallowCopyFieldState(src, dest));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsNullDest() {
TestObject src = new TestObject();
String dest = null;
ReflectionUtils.shallowCopyFieldState(src, dest);
assertThatIllegalArgumentException().isThrownBy(() ->
ReflectionUtils.shallowCopyFieldState(src, dest));
}
@Test

View File

@@ -19,6 +19,7 @@ package org.springframework.util;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
@@ -76,10 +77,11 @@ public class ResizableByteArrayOutputStreamTests {
assertByteArrayEqualsString(this.baos);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void failResize() throws Exception{
this.baos.write(helloBytes);
this.baos.resize(5);
assertThatIllegalArgumentException().isThrownBy(() ->
this.baos.resize(5));
}

View File

@@ -20,8 +20,9 @@ import java.math.BigInteger;
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.assertNotNull;
import static org.junit.Assert.assertNull;
/**
@@ -42,21 +43,23 @@ public class SerializationUtilsTests {
assertEquals("foo", SerializationUtils.deserialize(SerializationUtils.serialize("foo")));
}
@Test(expected = IllegalStateException.class)
@Test
public void deserializeUndefined() throws Exception {
byte[] bytes = FOO.toByteArray();
Object foo = SerializationUtils.deserialize(bytes);
assertNotNull(foo);
assertThatIllegalStateException().isThrownBy(() ->
SerializationUtils.deserialize(bytes));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void serializeNonSerializable() throws Exception {
SerializationUtils.serialize(new Object());
assertThatIllegalArgumentException().isThrownBy(() ->
SerializationUtils.serialize(new Object()));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void deserializeNonSerializable() throws Exception {
SerializationUtils.deserialize("foo".getBytes());
assertThatIllegalArgumentException().isThrownBy(() ->
SerializationUtils.deserialize("foo".getBytes()));
}
@Test

View File

@@ -22,6 +22,7 @@ import java.util.Properties;
import org.junit.Test;
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;
@@ -29,7 +30,6 @@ 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;
/**
* @author Rod Johnson
@@ -718,13 +718,8 @@ public class StringUtilsTests {
@Test // SPR-7779
public void testParseLocaleWithInvalidCharacters() {
try {
StringUtils.parseLocaleString("%0D%0AContent-length:30%0D%0A%0D%0A%3Cscript%3Ealert%28123%29%3C/script%3E");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
assertThatIllegalArgumentException().isThrownBy(() ->
StringUtils.parseLocaleString("%0D%0AContent-length:30%0D%0A%0D%0A%3Cscript%3Ealert%28123%29%3C/script%3E"));
}
@Test // SPR-9420

View File

@@ -20,6 +20,7 @@ import java.util.Map;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
/**
@@ -94,10 +95,10 @@ public class SystemPropertyUtilsTests {
assertEquals("Y#{foo.bar}X", resolved);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testReplaceWithNoDefault() {
String resolved = SystemPropertyUtils.resolvePlaceholders("${test.prop}");
assertEquals("", resolved);
assertThatIllegalArgumentException().isThrownBy(() ->
SystemPropertyUtils.resolvePlaceholders("${test.prop}"));
}
@Test

View File

@@ -20,6 +20,7 @@ import java.util.Comparator;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -36,14 +37,16 @@ public class InvertibleComparatorTests {
private final Comparator<Integer> comparator = new ComparableComparator<>();
@Test(expected = IllegalArgumentException.class)
@Test
public void shouldNeedComparator() throws Exception {
new InvertibleComparator<>(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new InvertibleComparator<>(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void shouldNeedComparatorWithAscending() throws Exception {
new InvertibleComparator<>(null, true);
assertThatIllegalArgumentException().isThrownBy(() ->
new InvertibleComparator<>(null, true));
}
@Test

View File

@@ -22,6 +22,8 @@ import java.util.concurrent.ExecutionException;
import org.junit.Test;
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.assertSame;
import static org.junit.Assert.fail;
@@ -49,7 +51,7 @@ public class ListenableFutureTaskTests {
}
@Override
public void onFailure(Throwable ex) {
fail(ex.getMessage());
throw new AssertionError(ex.getMessage(), ex);
}
});
task.run();
@@ -79,20 +81,12 @@ public class ListenableFutureTaskTests {
});
task.run();
try {
task.get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex) {
assertSame(s, ex.getCause().getMessage());
}
try {
task.completable().get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex) {
assertSame(s, ex.getCause().getMessage());
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
task::get)
.satisfies(ex -> assertThat(ex.getCause().getMessage()).isEqualTo(s));
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
task.completable()::get)
.satisfies(ex -> assertThat(ex.getCause().getMessage()).isEqualTo(s));
}
@Test
@@ -129,20 +123,12 @@ public class ListenableFutureTaskTests {
verify(failureCallback).onFailure(ex);
verifyZeroInteractions(successCallback);
try {
task.get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex2) {
assertSame(s, ex2.getCause().getMessage());
}
try {
task.completable().get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex2) {
assertSame(s, ex2.getCause().getMessage());
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
task::get)
.satisfies(e -> assertThat(e.getCause().getMessage()).isEqualTo(s));
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
task.completable()::get)
.satisfies(e -> assertThat(e.getCause().getMessage()).isEqualTo(s));
}
}

View File

@@ -24,6 +24,7 @@ import java.util.concurrent.TimeoutException;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
@@ -81,13 +82,9 @@ public class SettableListenableFutureTests {
Throwable exception = new RuntimeException();
assertTrue(settableListenableFuture.setException(exception));
try {
settableListenableFuture.get();
fail("Expected ExecutionException");
}
catch (ExecutionException ex) {
assertThat(ex.getCause(), equalTo(exception));
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
settableListenableFuture::get)
.withCause(exception);
assertFalse(settableListenableFuture.isCancelled());
assertTrue(settableListenableFuture.isDone());
@@ -99,13 +96,9 @@ public class SettableListenableFutureTests {
assertTrue(settableListenableFuture.setException(exception));
Future<String> completable = settableListenableFuture.completable();
try {
completable.get();
fail("Expected ExecutionException");
}
catch (ExecutionException ex) {
assertThat(ex.getCause(), equalTo(exception));
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
completable::get)
.withCause(exception);
assertFalse(completable.isCancelled());
assertTrue(completable.isDone());
@@ -116,13 +109,9 @@ public class SettableListenableFutureTests {
Throwable exception = new OutOfMemoryError();
assertTrue(settableListenableFuture.setException(exception));
try {
settableListenableFuture.get();
fail("Expected ExecutionException");
}
catch (ExecutionException ex) {
assertThat(ex.getCause(), equalTo(exception));
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
settableListenableFuture::get)
.withCause(exception);
assertFalse(settableListenableFuture.isCancelled());
assertTrue(settableListenableFuture.isDone());
@@ -134,13 +123,9 @@ public class SettableListenableFutureTests {
assertTrue(settableListenableFuture.setException(exception));
Future<String> completable = settableListenableFuture.completable();
try {
completable.get();
fail("Expected ExecutionException");
}
catch (ExecutionException ex) {
assertThat(ex.getCause(), equalTo(exception));
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
completable::get)
.withCause(exception);
assertFalse(completable.isCancelled());
assertTrue(completable.isDone());
@@ -158,7 +143,7 @@ public class SettableListenableFutureTests {
}
@Override
public void onFailure(Throwable ex) {
fail("Expected onSuccess() to be called");
throw new AssertionError("Expected onSuccess() to be called", ex);
}
});
@@ -180,7 +165,7 @@ public class SettableListenableFutureTests {
}
@Override
public void onFailure(Throwable ex) {
fail("Expected onSuccess() to be called");
throw new AssertionError("Expected onSuccess() to be called", ex);
}
});
@@ -269,13 +254,8 @@ public class SettableListenableFutureTests {
@Test
public void getWithTimeoutThrowsTimeoutException() throws ExecutionException, InterruptedException {
try {
settableListenableFuture.get(1L, TimeUnit.MILLISECONDS);
fail("Expected TimeoutException");
}
catch (TimeoutException ex) {
// expected
}
assertThatExceptionOfType(TimeoutException.class).isThrownBy(() ->
settableListenableFuture.get(1L, TimeUnit.MILLISECONDS));
}
@Test
@@ -362,13 +342,8 @@ public class SettableListenableFutureTests {
public void cancelStateThrowsExceptionWhenCallingGet() throws ExecutionException, InterruptedException {
settableListenableFuture.cancel(true);
try {
settableListenableFuture.get();
fail("Expected CancellationException");
}
catch (CancellationException ex) {
// expected
}
assertThatExceptionOfType(CancellationException.class).isThrownBy(() ->
settableListenableFuture.get());
assertTrue(settableListenableFuture.isCancelled());
assertTrue(settableListenableFuture.isDone());
@@ -389,13 +364,8 @@ public class SettableListenableFutureTests {
}
}).start();
try {
settableListenableFuture.get(500L, TimeUnit.MILLISECONDS);
fail("Expected CancellationException");
}
catch (CancellationException ex) {
// expected
}
assertThatExceptionOfType(CancellationException.class).isThrownBy(() ->
settableListenableFuture.get(500L, TimeUnit.MILLISECONDS));
assertTrue(settableListenableFuture.isCancelled());
assertTrue(settableListenableFuture.isDone());

View File

@@ -33,10 +33,9 @@ import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT;
import static javax.xml.stream.XMLStreamConstants.END_ELEMENT;
import static javax.xml.stream.XMLStreamConstants.START_DOCUMENT;
import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
/**
@@ -88,14 +87,9 @@ public class ListBasedXMLEventReaderTests {
assertEquals(START_DOCUMENT, reader.nextEvent().getEventType());
try {
reader.getElementText();
fail("Should have thrown XMLStreamException");
}
catch (XMLStreamException ex) {
// expected
assertTrue(ex.getMessage().startsWith("Not at START_ELEMENT"));
}
assertThatExceptionOfType(XMLStreamException.class).isThrownBy(
reader::getElementText)
.withMessageStartingWith("Not at START_ELEMENT");
}
private List<XMLEvent> readEvents(String xml) throws XMLStreamException {

View File

@@ -23,6 +23,8 @@ import javax.xml.XMLConstants;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
@@ -45,9 +47,10 @@ public class SimpleNamespaceContextTests {
private final SimpleNamespaceContext context = new SimpleNamespaceContext();
@Test(expected = IllegalArgumentException.class)
@Test
public void getNamespaceURI_withNull() throws Exception {
context.getNamespaceURI(null);
assertThatIllegalArgumentException().isThrownBy(() ->
context.getNamespaceURI(null));
}
@Test
@@ -72,9 +75,10 @@ public class SimpleNamespaceContextTests {
context.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX), is(defaultNamespaceUri));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void getPrefix_withNull() throws Exception {
context.getPrefix(null);
assertThatIllegalArgumentException().isThrownBy(() ->
context.getPrefix(null));
}
@Test
@@ -92,16 +96,18 @@ public class SimpleNamespaceContextTests {
anyOf(is("prefix1"), is("prefix2")));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void getPrefixes_withNull() throws Exception {
context.getPrefixes(null);
assertThatIllegalArgumentException().isThrownBy(() ->
context.getPrefixes(null));
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void getPrefixes_IteratorIsNotModifiable() throws Exception {
context.bindNamespaceUri(prefix, namespaceUri);
Iterator<String> iterator = context.getPrefixes(namespaceUri);
iterator.remove();
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(
iterator::remove);
}
@Test
@@ -120,14 +126,16 @@ public class SimpleNamespaceContextTests {
getItemSet(context.getPrefixes(namespaceUri)), is(makeSet("prefix1", "prefix2")));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void bindNamespaceUri_withNullNamespaceUri() {
context.bindNamespaceUri("prefix", null);
assertThatIllegalArgumentException().isThrownBy(() ->
context.bindNamespaceUri("prefix", null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void bindNamespaceUri_withNullPrefix() {
context.bindNamespaceUri(null, namespaceUri);
assertThatIllegalArgumentException().isThrownBy(() ->
context.bindNamespaceUri(null, namespaceUri));
}
@Test

View File

@@ -27,6 +27,7 @@ import javax.xml.transform.URIResolver;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@@ -72,19 +73,22 @@ public class TransformerUtilsTests {
assertEquals("no", indent);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void enableIndentingWithNullTransformer() throws Exception {
TransformerUtils.enableIndenting(null);
assertThatIllegalArgumentException().isThrownBy(() ->
TransformerUtils.enableIndenting(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void disableIndentingWithNullTransformer() throws Exception {
TransformerUtils.disableIndenting(null);
assertThatIllegalArgumentException().isThrownBy(() ->
TransformerUtils.disableIndenting(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void enableIndentingWithNegativeIndentAmount() throws Exception {
TransformerUtils.enableIndenting(new StubTransformer(), -21938);
assertThatIllegalArgumentException().isThrownBy(() ->
TransformerUtils.enableIndenting(new StubTransformer(), -21938));
}
@Test