Migrate Hamcrest assertions to AssertJ

Migrate all existing `assertThat(..., Matcher)` assertions to AssertJ
and add checkstyle rules to ensure they don't return.

See gh-23022
This commit is contained in:
Phillip Webb
2019-05-23 15:48:03 -07:00
parent 2294625cf0
commit 95a9d46a87
322 changed files with 4358 additions and 4814 deletions

View File

@@ -34,17 +34,15 @@ import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.springframework.core.CollectionFactory.createApproximateCollection;
import static org.springframework.core.CollectionFactory.createApproximateMap;
import static org.springframework.core.CollectionFactory.createCollection;
@@ -158,7 +156,7 @@ public class CollectionFactoryTests {
@Test
public void createApproximateCollectionFromEmptyHashSet() {
Collection<String> set = createApproximateCollection(new HashSet<String>(), 2);
assertThat(set, is(empty()));
Assertions.assertThat(set).isEmpty();
}
@Test
@@ -166,25 +164,25 @@ public class CollectionFactoryTests {
HashSet<String> hashSet = new HashSet<>();
hashSet.add("foo");
Collection<String> set = createApproximateCollection(hashSet, 2);
assertThat(set, is(empty()));
assertThat(set).isEmpty();
}
@Test
public void createApproximateCollectionFromEmptyEnumSet() {
Collection<Color> colors = createApproximateCollection(EnumSet.noneOf(Color.class), 2);
assertThat(colors, is(empty()));
assertThat(colors).isEmpty();
}
@Test
public void createApproximateCollectionFromNonEmptyEnumSet() {
Collection<Color> colors = createApproximateCollection(EnumSet.of(Color.BLUE), 2);
assertThat(colors, is(empty()));
assertThat(colors).isEmpty();
}
@Test
public void createApproximateMapFromEmptyHashMap() {
Map<String, String> map = createApproximateMap(new HashMap<String, String>(), 2);
assertThat(map.size(), is(0));
assertThat(map).isEmpty();
}
@Test
@@ -192,13 +190,13 @@ public class CollectionFactoryTests {
Map<String, String> hashMap = new HashMap<>();
hashMap.put("foo", "bar");
Map<String, String> map = createApproximateMap(hashMap, 2);
assertThat(map.size(), is(0));
assertThat(map).isEmpty();
}
@Test
public void createApproximateMapFromEmptyEnumMap() {
Map<Color, String> colors = createApproximateMap(new EnumMap<Color, String>(Color.class), 2);
assertThat(colors.size(), is(0));
assertThat(colors).isEmpty();
}
@Test
@@ -206,38 +204,38 @@ public class CollectionFactoryTests {
EnumMap<Color, String> enumMap = new EnumMap<>(Color.class);
enumMap.put(Color.BLUE, "blue");
Map<Color, String> colors = createApproximateMap(enumMap, 2);
assertThat(colors.size(), is(0));
assertThat(colors).isEmpty();
}
@Test
public void createsCollectionsCorrectly() {
// interfaces
assertThat(createCollection(List.class, 0), is(instanceOf(ArrayList.class)));
assertThat(createCollection(Set.class, 0), is(instanceOf(LinkedHashSet.class)));
assertThat(createCollection(Collection.class, 0), is(instanceOf(LinkedHashSet.class)));
assertThat(createCollection(SortedSet.class, 0), is(instanceOf(TreeSet.class)));
assertThat(createCollection(NavigableSet.class, 0), is(instanceOf(TreeSet.class)));
assertThat(createCollection(List.class, 0)).isInstanceOf(ArrayList.class);
assertThat(createCollection(Set.class, 0)).isInstanceOf(LinkedHashSet.class);
assertThat(createCollection(Collection.class, 0)).isInstanceOf(LinkedHashSet.class);
assertThat(createCollection(SortedSet.class, 0)).isInstanceOf(TreeSet.class);
assertThat(createCollection(NavigableSet.class, 0)).isInstanceOf(TreeSet.class);
assertThat(createCollection(List.class, String.class, 0), is(instanceOf(ArrayList.class)));
assertThat(createCollection(Set.class, String.class, 0), is(instanceOf(LinkedHashSet.class)));
assertThat(createCollection(Collection.class, String.class, 0), is(instanceOf(LinkedHashSet.class)));
assertThat(createCollection(SortedSet.class, String.class, 0), is(instanceOf(TreeSet.class)));
assertThat(createCollection(NavigableSet.class, String.class, 0), is(instanceOf(TreeSet.class)));
assertThat(createCollection(List.class, String.class, 0)).isInstanceOf(ArrayList.class);
assertThat(createCollection(Set.class, String.class, 0)).isInstanceOf(LinkedHashSet.class);
assertThat(createCollection(Collection.class, String.class, 0)).isInstanceOf(LinkedHashSet.class);
assertThat(createCollection(SortedSet.class, String.class, 0)).isInstanceOf(TreeSet.class);
assertThat(createCollection(NavigableSet.class, String.class, 0)).isInstanceOf(TreeSet.class);
// concrete types
assertThat(createCollection(HashSet.class, 0), is(instanceOf(HashSet.class)));
assertThat(createCollection(HashSet.class, String.class, 0), is(instanceOf(HashSet.class)));
assertThat(createCollection(HashSet.class, 0)).isInstanceOf(HashSet.class);
assertThat(createCollection(HashSet.class, String.class, 0)).isInstanceOf(HashSet.class);
}
@Test
public void createsEnumSet() {
assertThat(createCollection(EnumSet.class, Color.class, 0), is(instanceOf(EnumSet.class)));
assertThat(createCollection(EnumSet.class, Color.class, 0)).isInstanceOf(EnumSet.class);
}
@Test // SPR-17619
public void createsEnumSetSubclass() {
EnumSet<Color> enumSet = EnumSet.noneOf(Color.class);
assertThat(createCollection(enumSet.getClass(), Color.class, 0), is(instanceOf(enumSet.getClass())));
assertThat(createCollection(enumSet.getClass(), Color.class, 0)).isInstanceOf(enumSet.getClass());
}
@Test
@@ -261,25 +259,25 @@ public class CollectionFactoryTests {
@Test
public void createsMapsCorrectly() {
// interfaces
assertThat(createMap(Map.class, 0), is(instanceOf(LinkedHashMap.class)));
assertThat(createMap(SortedMap.class, 0), is(instanceOf(TreeMap.class)));
assertThat(createMap(NavigableMap.class, 0), is(instanceOf(TreeMap.class)));
assertThat(createMap(MultiValueMap.class, 0), is(instanceOf(LinkedMultiValueMap.class)));
assertThat(createMap(Map.class, 0)).isInstanceOf(LinkedHashMap.class);
assertThat(createMap(SortedMap.class, 0)).isInstanceOf(TreeMap.class);
assertThat(createMap(NavigableMap.class, 0)).isInstanceOf(TreeMap.class);
assertThat(createMap(MultiValueMap.class, 0)).isInstanceOf(LinkedMultiValueMap.class);
assertThat(createMap(Map.class, String.class, 0), is(instanceOf(LinkedHashMap.class)));
assertThat(createMap(SortedMap.class, String.class, 0), is(instanceOf(TreeMap.class)));
assertThat(createMap(NavigableMap.class, String.class, 0), is(instanceOf(TreeMap.class)));
assertThat(createMap(MultiValueMap.class, String.class, 0), is(instanceOf(LinkedMultiValueMap.class)));
assertThat(createMap(Map.class, String.class, 0)).isInstanceOf(LinkedHashMap.class);
assertThat(createMap(SortedMap.class, String.class, 0)).isInstanceOf(TreeMap.class);
assertThat(createMap(NavigableMap.class, String.class, 0)).isInstanceOf(TreeMap.class);
assertThat(createMap(MultiValueMap.class, String.class, 0)).isInstanceOf(LinkedMultiValueMap.class);
// concrete types
assertThat(createMap(HashMap.class, 0), is(instanceOf(HashMap.class)));
assertThat(createMap(HashMap.class, 0)).isInstanceOf(HashMap.class);
assertThat(createMap(HashMap.class, String.class, 0), is(instanceOf(HashMap.class)));
assertThat(createMap(HashMap.class, String.class, 0)).isInstanceOf(HashMap.class);
}
@Test
public void createsEnumMap() {
assertThat(createMap(EnumMap.class, Color.class, 0), is(instanceOf(EnumMap.class)));
assertThat(createMap(EnumMap.class, Color.class, 0)).isInstanceOf(EnumMap.class);
}
@Test

View File

@@ -27,8 +27,7 @@ import java.util.Map;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -112,25 +111,25 @@ public class GenericTypeResolverTests {
Map<TypeVariable, Type> map;
map = GenericTypeResolver.getTypeVariableMap(MySimpleInterfaceType.class);
assertThat(map.toString(), equalTo("{T=class java.lang.String}"));
assertThat(map.toString()).isEqualTo("{T=class java.lang.String}");
map = GenericTypeResolver.getTypeVariableMap(MyCollectionInterfaceType.class);
assertThat(map.toString(), equalTo("{T=java.util.Collection<java.lang.String>}"));
assertThat(map.toString()).isEqualTo("{T=java.util.Collection<java.lang.String>}");
map = GenericTypeResolver.getTypeVariableMap(MyCollectionSuperclassType.class);
assertThat(map.toString(), equalTo("{T=java.util.Collection<java.lang.String>}"));
assertThat(map.toString()).isEqualTo("{T=java.util.Collection<java.lang.String>}");
map = GenericTypeResolver.getTypeVariableMap(MySimpleTypeWithMethods.class);
assertThat(map.toString(), equalTo("{T=class java.lang.Integer}"));
assertThat(map.toString()).isEqualTo("{T=class java.lang.Integer}");
map = GenericTypeResolver.getTypeVariableMap(TopLevelClass.class);
assertThat(map.toString(), equalTo("{}"));
assertThat(map.toString()).isEqualTo("{}");
map = GenericTypeResolver.getTypeVariableMap(TypedTopLevelClass.class);
assertThat(map.toString(), equalTo("{T=class java.lang.Integer}"));
assertThat(map.toString()).isEqualTo("{T=class java.lang.Integer}");
map = GenericTypeResolver.getTypeVariableMap(TypedTopLevelClass.TypedNested.class);
assertThat(map.size(), equalTo(2));
assertThat(map.size()).isEqualTo(2);
Type t = null;
Type x = null;
for (Map.Entry<TypeVariable, Type> entry : map.entrySet()) {
@@ -141,8 +140,8 @@ public class GenericTypeResolverTests {
x = entry.getValue();
}
}
assertThat(t, equalTo((Type) Integer.class));
assertThat(x, equalTo((Type) Long.class));
assertThat(t).isEqualTo(Integer.class);
assertThat(x).isEqualTo(Long.class);
}
@Test // SPR-11030
@@ -162,14 +161,14 @@ public class GenericTypeResolverTests {
MethodParameter methodParameter = MethodParameter.forExecutable(
WithArrayBase.class.getDeclaredMethod("array", Object[].class), 0);
Class<?> resolved = GenericTypeResolver.resolveParameterType(methodParameter, WithArray.class);
assertThat(resolved, equalTo((Class<?>) Object[].class));
assertThat(resolved).isEqualTo(Object[].class);
}
@Test // SPR-11044
public void getGenericsOnArrayFromReturnCannotBeResolved() throws Exception {
Class<?> resolved = GenericTypeResolver.resolveReturnType(
WithArrayBase.class.getDeclaredMethod("array", Object[].class), WithArray.class);
assertThat(resolved, equalTo((Class<?>) Object[].class));
assertThat(resolved).isEqualTo(Object[].class);
}
@Test // SPR-11763

View File

@@ -31,8 +31,9 @@ import java.util.List;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SerializableTypeWrapper}.
@@ -44,7 +45,7 @@ public class SerializableTypeWrapperTests {
@Test
public void forField() throws Exception {
Type type = SerializableTypeWrapper.forField(Fields.class.getField("parameterizedType"));
assertThat(type.toString(), equalTo("java.util.List<java.lang.String>"));
assertThat(type.toString()).isEqualTo("java.util.List<java.lang.String>");
assertSerializable(type);
}
@@ -52,7 +53,7 @@ public class SerializableTypeWrapperTests {
public void forMethodParameter() throws Exception {
Method method = Methods.class.getDeclaredMethod("method", Class.class, Object.class);
Type type = SerializableTypeWrapper.forMethodParameter(MethodParameter.forExecutable(method, 0));
assertThat(type.toString(), equalTo("java.lang.Class<T>"));
assertThat(type.toString()).isEqualTo("java.lang.Class<T>");
assertSerializable(type);
}
@@ -60,21 +61,21 @@ public class SerializableTypeWrapperTests {
public void forConstructor() throws Exception {
Constructor<?> constructor = Constructors.class.getDeclaredConstructor(List.class);
Type type = SerializableTypeWrapper.forMethodParameter(MethodParameter.forExecutable(constructor, 0));
assertThat(type.toString(), equalTo("java.util.List<java.lang.String>"));
assertThat(type.toString()).isEqualTo("java.util.List<java.lang.String>");
assertSerializable(type);
}
@Test
public void classType() throws Exception {
Type type = SerializableTypeWrapper.forField(Fields.class.getField("classType"));
assertThat(type.toString(), equalTo("class java.lang.String"));
assertThat(type.toString()).isEqualTo("class java.lang.String");
assertSerializable(type);
}
@Test
public void genericArrayType() throws Exception {
GenericArrayType type = (GenericArrayType) SerializableTypeWrapper.forField(Fields.class.getField("genericArrayType"));
assertThat(type.toString(), equalTo("java.util.List<java.lang.String>[]"));
assertThat(type.toString()).isEqualTo("java.util.List<java.lang.String>[]");
assertSerializable(type);
assertSerializable(type.getGenericComponentType());
}
@@ -82,7 +83,7 @@ public class SerializableTypeWrapperTests {
@Test
public void parameterizedType() throws Exception {
ParameterizedType type = (ParameterizedType) SerializableTypeWrapper.forField(Fields.class.getField("parameterizedType"));
assertThat(type.toString(), equalTo("java.util.List<java.lang.String>"));
assertThat(type.toString()).isEqualTo("java.util.List<java.lang.String>");
assertSerializable(type);
assertSerializable(type.getOwnerType());
assertSerializable(type.getRawType());
@@ -93,7 +94,7 @@ public class SerializableTypeWrapperTests {
@Test
public void typeVariableType() throws Exception {
TypeVariable<?> type = (TypeVariable<?>) SerializableTypeWrapper.forField(Fields.class.getField("typeVariableType"));
assertThat(type.toString(), equalTo("T"));
assertThat(type.toString()).isEqualTo("T");
assertSerializable(type);
assertSerializable(type.getBounds());
}
@@ -102,7 +103,7 @@ public class SerializableTypeWrapperTests {
public void wildcardType() throws Exception {
ParameterizedType typeSource = (ParameterizedType) SerializableTypeWrapper.forField(Fields.class.getField("wildcardType"));
WildcardType type = (WildcardType) typeSource.getActualTypeArguments()[0];
assertThat(type.toString(), equalTo("? extends java.lang.CharSequence"));
assertThat(type.toString()).isEqualTo("? extends java.lang.CharSequence");
assertSerializable(type);
assertSerializable(type.getLowerBounds());
assertSerializable(type.getUpperBounds());
@@ -115,7 +116,7 @@ public class SerializableTypeWrapperTests {
oos.writeObject(source);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
assertThat(ois.readObject(), equalTo(source));
assertThat(ois.readObject()).isEqualTo(source);
}

View File

@@ -22,8 +22,8 @@ import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for StandardReflectionParameterNameDiscoverer
@@ -42,7 +42,7 @@ public class StandardReflectionParameterNameDiscoverTests {
public void getParameterNamesOnInterface() {
Method method = ReflectionUtils.findMethod(MessageService.class,"sendMessage", String.class);
String[] actualParams = parameterNameDiscoverer.getParameterNames(method);
assertThat(actualParams, is(new String[]{"message"}));
assertThat(actualParams).isEqualTo(new String[]{"message"});
}
public interface MessageService {

View File

@@ -25,10 +25,8 @@ import org.junit.Test;
import org.springframework.core.annotation.AnnotationUtilsTests.ImplicitAliasesContextConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@@ -64,16 +62,16 @@ public class AnnotationAttributesTests {
attributes.put("anno", nestedAttributes);
attributes.put("annoArray", new AnnotationAttributes[] {nestedAttributes});
assertThat(attributes.getString("name"), equalTo("dave"));
assertThat(attributes.getStringArray("names"), equalTo(new String[] {"dave", "frank", "hal"}));
assertThat(attributes.getBoolean("bool1"), equalTo(true));
assertThat(attributes.getBoolean("bool2"), equalTo(false));
assertThat(attributes.<Color>getEnum("color"), equalTo(Color.RED));
assertThat(attributes.getString("name")).isEqualTo("dave");
assertThat(attributes.getStringArray("names")).isEqualTo(new String[] {"dave", "frank", "hal"});
assertThat(attributes.getBoolean("bool1")).isEqualTo(true);
assertThat(attributes.getBoolean("bool2")).isEqualTo(false);
assertThat(attributes.<Color>getEnum("color")).isEqualTo(Color.RED);
assertTrue(attributes.getClass("class").equals(Integer.class));
assertThat(attributes.getClassArray("classes"), equalTo(new Class<?>[] {Number.class, Short.class, Integer.class}));
assertThat(attributes.<Integer>getNumber("number"), equalTo(42));
assertThat(attributes.getAnnotation("anno").<Integer>getNumber("value"), equalTo(10));
assertThat(attributes.getAnnotationArray("annoArray")[0].getString("name"), equalTo("algernon"));
assertThat(attributes.getClassArray("classes")).isEqualTo(new Class<?>[] {Number.class, Short.class, Integer.class});
assertThat(attributes.<Integer>getNumber("number")).isEqualTo(42);
assertThat(attributes.getAnnotation("anno").<Integer>getNumber("value")).isEqualTo(10);
assertThat(attributes.getAnnotationArray("annoArray")[0].getString("name")).isEqualTo("algernon");
}
@@ -99,18 +97,18 @@ public class AnnotationAttributesTests {
attributes.put("filters", filter);
// Get back arrays of single elements
assertThat(attributes.getStringArray("names"), equalTo(new String[] {"Dogbert"}));
assertThat(attributes.getClassArray("classes"), equalTo(new Class<?>[] {Number.class}));
assertThat(attributes.getStringArray("names")).isEqualTo(new String[] {"Dogbert"});
assertThat(attributes.getClassArray("classes")).isEqualTo(new Class<?>[] {Number.class});
AnnotationAttributes[] array = attributes.getAnnotationArray("nestedAttributes");
assertNotNull(array);
assertThat(array.length, is(1));
assertThat(array[0].getString("name"), equalTo("Dilbert"));
assertThat(array.length).isEqualTo(1);
assertThat(array[0].getString("name")).isEqualTo("Dilbert");
Filter[] filters = attributes.getAnnotationArray("filters", Filter.class);
assertNotNull(filters);
assertThat(filters.length, is(1));
assertThat(filters[0].pattern(), equalTo("foo"));
assertThat(filters.length).isEqualTo(1);
assertThat(filters[0].pattern()).isEqualTo("foo");
}
@Test
@@ -121,13 +119,13 @@ public class AnnotationAttributesTests {
attributes.put("filters", new Filter[] {filter, filter});
Filter retrievedFilter = attributes.getAnnotation("filter", Filter.class);
assertThat(retrievedFilter, equalTo(filter));
assertThat(retrievedFilter.pattern(), equalTo("foo"));
assertThat(retrievedFilter).isEqualTo(filter);
assertThat(retrievedFilter.pattern()).isEqualTo("foo");
Filter[] retrievedFilters = attributes.getAnnotationArray("filters", Filter.class);
assertNotNull(retrievedFilters);
assertEquals(2, retrievedFilters.length);
assertThat(retrievedFilters[1].pattern(), equalTo("foo"));
assertThat(retrievedFilters[1].pattern()).isEqualTo("foo");
}
@Test

View File

@@ -22,9 +22,7 @@ import javax.annotation.Priority;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@@ -37,7 +35,7 @@ public class AnnotationAwareOrderComparatorTests {
@Test
public void instanceVariableIsAnAnnotationAwareOrderComparator() {
assertThat(AnnotationAwareOrderComparator.INSTANCE, is(instanceOf(AnnotationAwareOrderComparator.class)));
assertThat(AnnotationAwareOrderComparator.INSTANCE).isInstanceOf(AnnotationAwareOrderComparator.class);
}
@Test

View File

@@ -43,10 +43,9 @@ import org.springframework.stereotype.Component;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -581,7 +580,7 @@ public class AnnotationUtilsTests {
Set<MyRepeatable> annotations = getRepeatableAnnotations(method, MyRepeatable.class, MyRepeatableContainer.class);
assertNotNull(annotations);
List<String> values = annotations.stream().map(MyRepeatable::value).collect(toList());
assertThat(values, is(asList("A", "B", "C", "meta1")));
assertThat(values).isEqualTo(asList("A", "B", "C", "meta1"));
}
@Test
@@ -606,10 +605,10 @@ public class AnnotationUtilsTests {
assertNotNull(annotations);
List<String> locations = annotations.stream().map(ContextConfig::location).collect(toList());
assertThat(locations, is(expectedLocations));
assertThat(locations).isEqualTo(expectedLocations);
List<String> values = annotations.stream().map(ContextConfig::value).collect(toList());
assertThat(values, is(expectedLocations));
assertThat(values).isEqualTo(expectedLocations);
}
@Test
@@ -621,19 +620,19 @@ public class AnnotationUtilsTests {
MyRepeatable[] array = MyRepeatableClass.class.getAnnotationsByType(MyRepeatable.class);
assertNotNull(array);
List<String> values = stream(array).map(MyRepeatable::value).collect(toList());
assertThat(values, is(expectedValuesJava));
assertThat(values).isEqualTo(expectedValuesJava);
// Spring
Set<MyRepeatable> set = getRepeatableAnnotations(MyRepeatableClass.class, MyRepeatable.class, MyRepeatableContainer.class);
assertNotNull(set);
values = set.stream().map(MyRepeatable::value).collect(toList());
assertThat(values, is(expectedValuesSpring));
assertThat(values).isEqualTo(expectedValuesSpring);
// When container type is omitted and therefore inferred from @Repeatable
set = getRepeatableAnnotations(MyRepeatableClass.class, MyRepeatable.class);
assertNotNull(set);
values = set.stream().map(MyRepeatable::value).collect(toList());
assertThat(values, is(expectedValuesSpring));
assertThat(values).isEqualTo(expectedValuesSpring);
}
@Test
@@ -646,19 +645,19 @@ public class AnnotationUtilsTests {
MyRepeatable[] array = clazz.getAnnotationsByType(MyRepeatable.class);
assertNotNull(array);
List<String> values = stream(array).map(MyRepeatable::value).collect(toList());
assertThat(values, is(expectedValuesJava));
assertThat(values).isEqualTo(expectedValuesJava);
// Spring
Set<MyRepeatable> set = getRepeatableAnnotations(clazz, MyRepeatable.class, MyRepeatableContainer.class);
assertNotNull(set);
values = set.stream().map(MyRepeatable::value).collect(toList());
assertThat(values, is(expectedValuesSpring));
assertThat(values).isEqualTo(expectedValuesSpring);
// When container type is omitted and therefore inferred from @Repeatable
set = getRepeatableAnnotations(clazz, MyRepeatable.class);
assertNotNull(set);
values = set.stream().map(MyRepeatable::value).collect(toList());
assertThat(values, is(expectedValuesSpring));
assertThat(values).isEqualTo(expectedValuesSpring);
}
@Test
@@ -671,19 +670,19 @@ public class AnnotationUtilsTests {
MyRepeatable[] array = clazz.getAnnotationsByType(MyRepeatable.class);
assertNotNull(array);
List<String> values = stream(array).map(MyRepeatable::value).collect(toList());
assertThat(values, is(expectedValuesJava));
assertThat(values).isEqualTo(expectedValuesJava);
// Spring
Set<MyRepeatable> set = getRepeatableAnnotations(clazz, MyRepeatable.class, MyRepeatableContainer.class);
assertNotNull(set);
values = set.stream().map(MyRepeatable::value).collect(toList());
assertThat(values, is(expectedValuesSpring));
assertThat(values).isEqualTo(expectedValuesSpring);
// When container type is omitted and therefore inferred from @Repeatable
set = getRepeatableAnnotations(clazz, MyRepeatable.class);
assertNotNull(set);
values = set.stream().map(MyRepeatable::value).collect(toList());
assertThat(values, is(expectedValuesSpring));
assertThat(values).isEqualTo(expectedValuesSpring);
}
@Test
@@ -696,19 +695,19 @@ public class AnnotationUtilsTests {
MyRepeatable[] array = clazz.getAnnotationsByType(MyRepeatable.class);
assertNotNull(array);
List<String> values = stream(array).map(MyRepeatable::value).collect(toList());
assertThat(values, is(expectedValuesJava));
assertThat(values).isEqualTo(expectedValuesJava);
// Spring
Set<MyRepeatable> set = getRepeatableAnnotations(clazz, MyRepeatable.class, MyRepeatableContainer.class);
assertNotNull(set);
values = set.stream().map(MyRepeatable::value).collect(toList());
assertThat(values, is(expectedValuesSpring));
assertThat(values).isEqualTo(expectedValuesSpring);
// When container type is omitted and therefore inferred from @Repeatable
set = getRepeatableAnnotations(clazz, MyRepeatable.class);
assertNotNull(set);
values = set.stream().map(MyRepeatable::value).collect(toList());
assertThat(values, is(expectedValuesSpring));
assertThat(values).isEqualTo(expectedValuesSpring);
}
@Test
@@ -720,19 +719,19 @@ public class AnnotationUtilsTests {
MyRepeatable[] array = MyRepeatableClass.class.getDeclaredAnnotationsByType(MyRepeatable.class);
assertNotNull(array);
List<String> values = stream(array).map(MyRepeatable::value).collect(toList());
assertThat(values, is(expectedValuesJava));
assertThat(values).isEqualTo(expectedValuesJava);
// Spring
Set<MyRepeatable> set = getDeclaredRepeatableAnnotations(MyRepeatableClass.class, MyRepeatable.class, MyRepeatableContainer.class);
assertNotNull(set);
values = set.stream().map(MyRepeatable::value).collect(toList());
assertThat(values, is(expectedValuesSpring));
assertThat(values).isEqualTo(expectedValuesSpring);
// When container type is omitted and therefore inferred from @Repeatable
set = getDeclaredRepeatableAnnotations(MyRepeatableClass.class, MyRepeatable.class);
assertNotNull(set);
values = set.stream().map(MyRepeatable::value).collect(toList());
assertThat(values, is(expectedValuesSpring));
assertThat(values).isEqualTo(expectedValuesSpring);
}
@Test
@@ -742,17 +741,17 @@ public class AnnotationUtilsTests {
// Java 8
MyRepeatable[] array = clazz.getDeclaredAnnotationsByType(MyRepeatable.class);
assertNotNull(array);
assertThat(array.length, is(0));
assertThat(array.length).isEqualTo(0);
// Spring
Set<MyRepeatable> set = getDeclaredRepeatableAnnotations(clazz, MyRepeatable.class, MyRepeatableContainer.class);
assertNotNull(set);
assertThat(set.size(), is(0));
assertThat(set).hasSize(0);
// When container type is omitted and therefore inferred from @Repeatable
set = getDeclaredRepeatableAnnotations(clazz, MyRepeatable.class);
assertNotNull(set);
assertThat(set.size(), is(0));
assertThat(set).hasSize(0);
}
@Test

View File

@@ -42,10 +42,8 @@ import org.springframework.core.MethodParameter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
@@ -742,29 +740,29 @@ public class TypeDescriptorTests {
ObjectInputStream inputStream = new ObjectInputStream(new ByteArrayInputStream(
out.toByteArray()));
TypeDescriptor readObject = (TypeDescriptor) inputStream.readObject();
assertThat(readObject, equalTo(typeDescriptor));
assertThat(readObject).isEqualTo(typeDescriptor);
}
@Test
public void createCollectionWithNullElement() throws Exception {
TypeDescriptor typeDescriptor = TypeDescriptor.collection(List.class, null);
assertThat(typeDescriptor.getElementTypeDescriptor(), nullValue());
assertThat(typeDescriptor.getElementTypeDescriptor()).isNull();
}
@Test
public void createMapWithNullElements() throws Exception {
TypeDescriptor typeDescriptor = TypeDescriptor.map(LinkedHashMap.class, null, null);
assertThat(typeDescriptor.getMapKeyTypeDescriptor(), nullValue());
assertThat(typeDescriptor.getMapValueTypeDescriptor(), nullValue());
assertThat(typeDescriptor.getMapKeyTypeDescriptor()).isNull();
assertThat(typeDescriptor.getMapValueTypeDescriptor()).isNull();
}
@Test
public void getSource() throws Exception {
Field field = getClass().getField("fieldScalar");
MethodParameter methodParameter = new MethodParameter(getClass().getMethod("testParameterPrimitive", int.class), 0);
assertThat(new TypeDescriptor(field).getSource(), equalTo((Object) field));
assertThat(new TypeDescriptor(methodParameter).getSource(), equalTo((Object) methodParameter));
assertThat(TypeDescriptor.valueOf(Integer.class).getSource(), equalTo((Object) Integer.class));
assertThat(new TypeDescriptor(field).getSource()).isEqualTo(field);
assertThat(new TypeDescriptor(methodParameter).getSource()).isEqualTo(methodParameter);
assertThat(TypeDescriptor.valueOf(Integer.class).getSource()).isEqualTo(Integer.class);
}

View File

@@ -29,10 +29,9 @@ 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.assertThat;
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;
/**
* Tests for {@link ConvertingComparator}.
@@ -91,9 +90,9 @@ public class ConvertingComparatorTests {
}
private void testConversion(ConvertingComparator<String, Integer> convertingComparator) {
assertThat(convertingComparator.compare("0", "0"), is(0));
assertThat(convertingComparator.compare("0", "1"), is(-1));
assertThat(convertingComparator.compare("1", "0"), is(1));
assertThat(convertingComparator.compare("0", "0")).isEqualTo(0);
assertThat(convertingComparator.compare("0", "1")).isEqualTo(-1);
assertThat(convertingComparator.compare("1", "0")).isEqualTo(1);
comparator.assertCalled();
}
@@ -102,7 +101,7 @@ public class ConvertingComparatorTests {
ArrayList<Entry<String, Integer>> list = createReverseOrderMapEntryList();
Comparator<Map.Entry<String, Integer>> comparator = ConvertingComparator.mapEntryKeys(new ComparableComparator<String>());
Collections.sort(list, comparator);
assertThat(list.get(0).getKey(), is("a"));
assertThat(list.get(0).getKey()).isEqualTo("a");
}
@Test
@@ -110,7 +109,7 @@ public class ConvertingComparatorTests {
ArrayList<Entry<String, Integer>> list = createReverseOrderMapEntryList();
Comparator<Map.Entry<String, Integer>> comparator = ConvertingComparator.mapEntryValues(new ComparableComparator<Integer>());
Collections.sort(list, comparator);
assertThat(list.get(0).getValue(), is(1));
assertThat(list.get(0).getValue()).isEqualTo(1);
}
private ArrayList<Entry<String, Integer>> createReverseOrderMapEntryList() {
@@ -119,7 +118,7 @@ public class ConvertingComparatorTests {
map.put("a", 1);
ArrayList<Entry<String, Integer>> list = new ArrayList<>(
map.entrySet());
assertThat(list.get(0).getKey(), is("b"));
assertThat(list.get(0).getKey()).isEqualTo("b");
return list;
}
@@ -139,14 +138,14 @@ public class ConvertingComparatorTests {
@Override
public int compare(Integer o1, Integer o2) {
assertThat(o1, instanceOf(Integer.class));
assertThat(o2, instanceOf(Integer.class));
assertThat(o1).isInstanceOf(Integer.class);
assertThat(o2).isInstanceOf(Integer.class);
this.called = true;
return super.compare(o1, o2);
};
public void assertCalled() {
assertThat(this.called, is(true));
assertThat(this.called).isTrue();
}
}

View File

@@ -56,9 +56,8 @@ import org.springframework.tests.TestGroup;
import org.springframework.util.ClassUtils;
import org.springframework.util.StopWatch;
import static org.assertj.core.api.Assertions.assertThat;
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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -657,7 +656,7 @@ public class DefaultConversionServiceTests {
public void convertByteArrayToWrapperArray() {
byte[] byteArray = new byte[] {1, 2, 3};
Byte[] converted = conversionService.convert(byteArray, Byte[].class);
assertThat(converted, equalTo(new Byte[]{1, 2, 3}));
assertThat(converted).isEqualTo(new Byte[]{1, 2, 3});
}
@Test
@@ -914,20 +913,20 @@ public class DefaultConversionServiceTests {
@Test
public void convertCharArrayToString() {
String converted = conversionService.convert(new char[] {'a', 'b', 'c'}, String.class);
assertThat(converted, equalTo("a,b,c"));
assertThat(converted).isEqualTo("a,b,c");
}
@Test
public void convertStringToCharArray() {
char[] converted = conversionService.convert("a,b,c", char[].class);
assertThat(converted, equalTo(new char[]{'a', 'b', 'c'}));
assertThat(converted).isEqualTo(new char[]{'a', 'b', 'c'});
}
@Test
public void convertStringToCustomCharArray() {
conversionService.addConverter(String.class, char[].class, String::toCharArray);
char[] converted = conversionService.convert("abc", char[].class);
assertThat(converted, equalTo(new char[] {'a', 'b', 'c'}));
assertThat(converted).isEqualTo(new char[] {'a', 'b', 'c'});
}
@Test

View File

@@ -23,10 +23,11 @@ import org.junit.Test;
import org.springframework.core.convert.converter.Converter;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.sameInstance;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ByteBufferConverter}.
@@ -51,8 +52,8 @@ public class ByteBufferConverterTests {
public void byteArrayToByteBuffer() throws Exception {
byte[] bytes = new byte[] { 1, 2, 3 };
ByteBuffer convert = this.conversionService.convert(bytes, ByteBuffer.class);
assertThat(convert.array(), not(sameInstance(bytes)));
assertThat(convert.array(), equalTo(bytes));
assertThat(convert.array()).isNotSameAs(bytes);
assertThat(convert.array()).isEqualTo(bytes);
}
@Test
@@ -60,8 +61,8 @@ public class ByteBufferConverterTests {
byte[] bytes = new byte[] { 1, 2, 3 };
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
byte[] convert = this.conversionService.convert(byteBuffer, byte[].class);
assertThat(convert, not(sameInstance(bytes)));
assertThat(convert, equalTo(bytes));
assertThat(convert).isNotSameAs(bytes);
assertThat(convert).isEqualTo(bytes);
}
@Test
@@ -69,8 +70,8 @@ public class ByteBufferConverterTests {
byte[] bytes = new byte[] { 1, 2, 3 };
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
OtherType convert = this.conversionService.convert(byteBuffer, OtherType.class);
assertThat(convert.bytes, not(sameInstance(bytes)));
assertThat(convert.bytes, equalTo(bytes));
assertThat(convert.bytes).isNotSameAs(bytes);
assertThat(convert.bytes).isEqualTo(bytes);
}
@Test
@@ -78,8 +79,8 @@ public class ByteBufferConverterTests {
byte[] bytes = new byte[] { 1, 2, 3 };
OtherType otherType = new OtherType(bytes);
ByteBuffer convert = this.conversionService.convert(otherType, ByteBuffer.class);
assertThat(convert.array(), not(sameInstance(bytes)));
assertThat(convert.array(), equalTo(bytes));
assertThat(convert.array()).isNotSameAs(bytes);
assertThat(convert.array()).isEqualTo(bytes);
}
@Test
@@ -87,10 +88,10 @@ public class ByteBufferConverterTests {
byte[] bytes = new byte[] { 1, 2, 3 };
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
ByteBuffer convert = this.conversionService.convert(byteBuffer, ByteBuffer.class);
assertThat(convert, not(sameInstance(byteBuffer.rewind())));
assertThat(convert, equalTo(byteBuffer.rewind()));
assertThat(convert, equalTo(ByteBuffer.wrap(bytes)));
assertThat(convert.array(), equalTo(bytes));
assertThat(convert).isNotSameAs(byteBuffer.rewind());
assertThat(convert).isEqualTo(byteBuffer.rewind());
assertThat(convert).isEqualTo(ByteBuffer.wrap(bytes));
assertThat(convert.array()).isEqualTo(bytes);
}

View File

@@ -51,11 +51,10 @@ 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.assertThat;
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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -527,7 +526,7 @@ public class GenericConversionServiceTests {
MyConditionalGenericConverter converter = new MyConditionalGenericConverter();
conversionService.addConverter(converter);
assertEquals((Integer) 3, conversionService.convert(3, Integer.class));
assertThat(converter.getSourceTypes().size(), greaterThan(2));
assertThat(converter.getSourceTypes().size()).isGreaterThan(2);
assertTrue(converter.getSourceTypes().stream().allMatch(td -> Integer.class.equals(td.getType())));
}

View File

@@ -33,9 +33,8 @@ import org.springframework.core.convert.TypeDescriptor;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
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;
@@ -245,9 +244,9 @@ public class MapToMapConverterTests {
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("multiValueMapTarget"));
MultiValueMap<String, String> converted = (MultiValueMap<String, String>) conversionService.convert(source, targetType);
assertThat(converted.size(), equalTo(2));
assertThat(converted.get("a"), equalTo(Arrays.asList("1", "2", "3")));
assertThat(converted.get("b"), equalTo(Arrays.asList("4", "5", "6")));
assertThat(converted.size()).isEqualTo(2);
assertThat(converted.get("a")).isEqualTo(Arrays.asList("1", "2", "3"));
assertThat(converted.get("b")).isEqualTo(Arrays.asList("4", "5", "6"));
}
@Test
@@ -260,9 +259,9 @@ public class MapToMapConverterTests {
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("multiValueMapTarget"));
MultiValueMap<String, String> converted = (MultiValueMap<String, String>) conversionService.convert(source, targetType);
assertThat(converted.size(), equalTo(2));
assertThat(converted.get("a"), equalTo(Arrays.asList("1")));
assertThat(converted.get("b"), equalTo(Arrays.asList("2")));
assertThat(converted.size()).isEqualTo(2);
assertThat(converted.get("a")).isEqualTo(Arrays.asList("1"));
assertThat(converted.get("b")).isEqualTo(Arrays.asList("2"));
}
@Test

View File

@@ -22,8 +22,8 @@ import java.util.Set;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests covering the extensibility of {@link AbstractEnvironment}.
@@ -38,7 +38,7 @@ public class CustomEnvironmentTests {
@Test
public void control() {
Environment env = new AbstractEnvironment() { };
assertThat(env.acceptsProfiles(defaultProfile()), is(true));
assertThat(env.acceptsProfiles(defaultProfile())).isTrue();
}
@Test
@@ -51,7 +51,7 @@ public class CustomEnvironmentTests {
}
Environment env = new CustomEnvironment();
assertThat(env.acceptsProfiles(defaultProfile()), is(false));
assertThat(env.acceptsProfiles(defaultProfile())).isFalse();
}
@Test
@@ -64,8 +64,8 @@ public class CustomEnvironmentTests {
}
Environment env = new CustomEnvironment();
assertThat(env.acceptsProfiles(defaultProfile()), is(false));
assertThat(env.acceptsProfiles(Profiles.of("rd1")), is(true));
assertThat(env.acceptsProfiles(defaultProfile())).isFalse();
assertThat(env.acceptsProfiles(Profiles.of("rd1"))).isTrue();
}
@Test
@@ -82,28 +82,28 @@ public class CustomEnvironmentTests {
}
ConfigurableEnvironment env = new CustomEnvironment();
assertThat(env.acceptsProfiles(defaultProfile()), is(false));
assertThat(env.acceptsProfiles(Profiles.of("rd1 | rd2")), is(true));
assertThat(env.acceptsProfiles(defaultProfile())).isFalse();
assertThat(env.acceptsProfiles(Profiles.of("rd1 | rd2"))).isTrue();
// finally, issue additional assertions to cover all combinations of calling these
// methods, however unlikely.
env.setDefaultProfiles("d1");
assertThat(env.acceptsProfiles(Profiles.of("rd1 | rd2")), is(false));
assertThat(env.acceptsProfiles(Profiles.of("d1")), is(true));
assertThat(env.acceptsProfiles(Profiles.of("rd1 | rd2"))).isFalse();
assertThat(env.acceptsProfiles(Profiles.of("d1"))).isTrue();
env.setActiveProfiles("a1", "a2");
assertThat(env.acceptsProfiles(Profiles.of("d1")), is(false));
assertThat(env.acceptsProfiles(Profiles.of("a1 | a2")), is(true));
assertThat(env.acceptsProfiles(Profiles.of("d1"))).isFalse();
assertThat(env.acceptsProfiles(Profiles.of("a1 | a2"))).isTrue();
env.setActiveProfiles();
assertThat(env.acceptsProfiles(Profiles.of("d1")), is(true));
assertThat(env.acceptsProfiles(Profiles.of("a1 | a2")), is(false));
assertThat(env.acceptsProfiles(Profiles.of("d1"))).isTrue();
assertThat(env.acceptsProfiles(Profiles.of("a1 | a2"))).isFalse();
env.setDefaultProfiles();
assertThat(env.acceptsProfiles(defaultProfile()), is(false));
assertThat(env.acceptsProfiles(Profiles.of("rd1 | rd2")), is(false));
assertThat(env.acceptsProfiles(Profiles.of("d1")), is(false));
assertThat(env.acceptsProfiles(Profiles.of("a1 | a2")), is(false));
assertThat(env.acceptsProfiles(defaultProfile())).isFalse();
assertThat(env.acceptsProfiles(Profiles.of("rd1 | rd2"))).isFalse();
assertThat(env.acceptsProfiles(Profiles.of("d1"))).isFalse();
assertThat(env.acceptsProfiles(Profiles.of("a1 | a2"))).isFalse();
}
private Profiles defaultProfile() {

View File

@@ -22,10 +22,7 @@ import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
/**
@@ -43,7 +40,7 @@ public class JOptCommandLinePropertySourceTests {
OptionSet options = parser.parse("--foo=bar");
PropertySource<?> ps = new JOptCommandLinePropertySource(options);
assertThat((String)ps.getProperty("foo"), equalTo("bar"));
assertThat((String)ps.getProperty("foo")).isEqualTo("bar");
}
@Test
@@ -53,8 +50,8 @@ public class JOptCommandLinePropertySourceTests {
OptionSet options = parser.parse("--foo");
PropertySource<?> ps = new JOptCommandLinePropertySource(options);
assertThat(ps.containsProperty("foo"), is(true));
assertThat((String)ps.getProperty("foo"), equalTo(""));
assertThat(ps.containsProperty("foo")).isTrue();
assertThat((String)ps.getProperty("foo")).isEqualTo("");
}
@Test
@@ -65,10 +62,10 @@ public class JOptCommandLinePropertySourceTests {
OptionSet options = parser.parse("--o1");
PropertySource<?> ps = new JOptCommandLinePropertySource(options);
assertThat(ps.containsProperty("o1"), is(true));
assertThat(ps.containsProperty("o2"), is(false));
assertThat((String)ps.getProperty("o1"), equalTo(""));
assertThat(ps.getProperty("o2"), nullValue());
assertThat(ps.containsProperty("o1")).isTrue();
assertThat(ps.containsProperty("o2")).isFalse();
assertThat((String)ps.getProperty("o1")).isEqualTo("");
assertThat(ps.getProperty("o2")).isNull();
}
@Test
@@ -79,7 +76,7 @@ public class JOptCommandLinePropertySourceTests {
CommandLinePropertySource<?> ps = new JOptCommandLinePropertySource(options);
assertEquals(Arrays.asList("bar","baz","biz"), ps.getOptionValues("foo"));
assertThat(ps.getProperty("foo"), equalTo("bar,baz,biz"));
assertThat(ps.getProperty("foo")).isEqualTo("bar,baz,biz");
}
@Test
@@ -90,7 +87,7 @@ public class JOptCommandLinePropertySourceTests {
CommandLinePropertySource<?> ps = new JOptCommandLinePropertySource(options);
assertEquals(Arrays.asList("bar","baz","biz"), ps.getOptionValues("foo"));
assertThat(ps.getProperty("foo"), equalTo("bar,baz,biz"));
assertThat(ps.getProperty("foo")).isEqualTo("bar,baz,biz");
}
@Test
@@ -100,7 +97,7 @@ public class JOptCommandLinePropertySourceTests {
OptionSet options = parser.parse(); // <-- no options whatsoever
PropertySource<?> ps = new JOptCommandLinePropertySource(options);
assertThat(ps.getProperty("foo"), nullValue());
assertThat(ps.getProperty("foo")).isNull();
}
@Test
@@ -110,7 +107,7 @@ public class JOptCommandLinePropertySourceTests {
OptionSet options = parser.parse("--spring.profiles.active=p1");
CommandLinePropertySource<?> ps = new JOptCommandLinePropertySource(options);
assertThat(ps.getProperty("spring.profiles.active"), equalTo("p1"));
assertThat(ps.getProperty("spring.profiles.active")).isEqualTo("p1");
}
@Test
@@ -121,13 +118,13 @@ public class JOptCommandLinePropertySourceTests {
OptionSet optionSet = parser.parse("--o1=v1", "--o2");
EnumerablePropertySource<?> ps = new JOptCommandLinePropertySource(optionSet);
assertThat(ps.containsProperty("nonOptionArgs"), is(false));
assertThat(ps.containsProperty("o1"), is(true));
assertThat(ps.containsProperty("o2"), is(true));
assertThat(ps.containsProperty("nonOptionArgs")).isFalse();
assertThat(ps.containsProperty("o1")).isTrue();
assertThat(ps.containsProperty("o2")).isTrue();
assertThat(ps.containsProperty("nonOptionArgs"), is(false));
assertThat(ps.getProperty("nonOptionArgs"), nullValue());
assertThat(ps.getPropertyNames().length, is(2));
assertThat(ps.containsProperty("nonOptionArgs")).isFalse();
assertThat(ps.getProperty("nonOptionArgs")).isNull();
assertThat(ps.getPropertyNames().length).isEqualTo(2);
}
@Test
@@ -138,12 +135,12 @@ public class JOptCommandLinePropertySourceTests {
OptionSet optionSet = parser.parse("--o1=v1", "noa1", "--o2", "noa2");
PropertySource<?> ps = new JOptCommandLinePropertySource(optionSet);
assertThat(ps.containsProperty("nonOptionArgs"), is(true));
assertThat(ps.containsProperty("o1"), is(true));
assertThat(ps.containsProperty("o2"), is(true));
assertThat(ps.containsProperty("nonOptionArgs")).isTrue();
assertThat(ps.containsProperty("o1")).isTrue();
assertThat(ps.containsProperty("o2")).isTrue();
String nonOptionArgs = (String)ps.getProperty("nonOptionArgs");
assertThat(nonOptionArgs, equalTo("noa1,noa2"));
assertThat(nonOptionArgs).isEqualTo("noa1,noa2");
}
@Test
@@ -155,12 +152,12 @@ public class JOptCommandLinePropertySourceTests {
CommandLinePropertySource<?> ps = new JOptCommandLinePropertySource(optionSet);
ps.setNonOptionArgsPropertyName("NOA");
assertThat(ps.containsProperty("nonOptionArgs"), is(false));
assertThat(ps.containsProperty("NOA"), is(true));
assertThat(ps.containsProperty("o1"), is(true));
assertThat(ps.containsProperty("o2"), is(true));
assertThat(ps.containsProperty("nonOptionArgs")).isFalse();
assertThat(ps.containsProperty("NOA")).isTrue();
assertThat(ps.containsProperty("o1")).isTrue();
assertThat(ps.containsProperty("o2")).isTrue();
String nonOptionArgs = ps.getProperty("NOA");
assertThat(nonOptionArgs, equalTo("noa1,noa2"));
assertThat(nonOptionArgs).isEqualTo("noa1,noa2");
}
@Test
@@ -170,7 +167,7 @@ public class JOptCommandLinePropertySourceTests {
OptionSet options = parser.parse("--o1=VAL_1");
PropertySource<?> ps = new JOptCommandLinePropertySource(options);
assertThat(ps.getProperty("o1"), equalTo("VAL_1"));
assertThat(ps.getProperty("o1")).isEqualTo("VAL_1");
}
public static enum OptionEnum {

View File

@@ -22,14 +22,9 @@ import org.junit.Test;
import org.springframework.mock.env.MockPropertySource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
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.assertNull;
@@ -48,68 +43,68 @@ public class MutablePropertySourcesTests {
sources.addLast(new MockPropertySource("d").withProperty("p1", "dValue"));
sources.addLast(new MockPropertySource("f").withProperty("p1", "fValue"));
assertThat(sources.size(), equalTo(3));
assertThat(sources.contains("a"), is(false));
assertThat(sources.contains("b"), is(true));
assertThat(sources.contains("c"), is(false));
assertThat(sources.contains("d"), is(true));
assertThat(sources.contains("e"), is(false));
assertThat(sources.contains("f"), is(true));
assertThat(sources.contains("g"), is(false));
assertThat(sources.size()).isEqualTo(3);
assertThat(sources.contains("a")).isFalse();
assertThat(sources.contains("b")).isTrue();
assertThat(sources.contains("c")).isFalse();
assertThat(sources.contains("d")).isTrue();
assertThat(sources.contains("e")).isFalse();
assertThat(sources.contains("f")).isTrue();
assertThat(sources.contains("g")).isFalse();
assertThat(sources.get("b"), not(nullValue()));
assertThat(sources.get("b").getProperty("p1"), equalTo("bValue"));
assertThat(sources.get("d"), not(nullValue()));
assertThat(sources.get("d").getProperty("p1"), equalTo("dValue"));
assertThat(sources.get("b")).isNotNull();
assertThat(sources.get("b").getProperty("p1")).isEqualTo("bValue");
assertThat(sources.get("d")).isNotNull();
assertThat(sources.get("d").getProperty("p1")).isEqualTo("dValue");
sources.addBefore("b", new MockPropertySource("a"));
sources.addAfter("b", new MockPropertySource("c"));
assertThat(sources.size(), equalTo(5));
assertThat(sources.precedenceOf(PropertySource.named("a")), is(0));
assertThat(sources.precedenceOf(PropertySource.named("b")), is(1));
assertThat(sources.precedenceOf(PropertySource.named("c")), is(2));
assertThat(sources.precedenceOf(PropertySource.named("d")), is(3));
assertThat(sources.precedenceOf(PropertySource.named("f")), is(4));
assertThat(sources.size()).isEqualTo(5);
assertThat(sources.precedenceOf(PropertySource.named("a"))).isEqualTo(0);
assertThat(sources.precedenceOf(PropertySource.named("b"))).isEqualTo(1);
assertThat(sources.precedenceOf(PropertySource.named("c"))).isEqualTo(2);
assertThat(sources.precedenceOf(PropertySource.named("d"))).isEqualTo(3);
assertThat(sources.precedenceOf(PropertySource.named("f"))).isEqualTo(4);
sources.addBefore("f", new MockPropertySource("e"));
sources.addAfter("f", new MockPropertySource("g"));
assertThat(sources.size(), equalTo(7));
assertThat(sources.precedenceOf(PropertySource.named("a")), is(0));
assertThat(sources.precedenceOf(PropertySource.named("b")), is(1));
assertThat(sources.precedenceOf(PropertySource.named("c")), is(2));
assertThat(sources.precedenceOf(PropertySource.named("d")), is(3));
assertThat(sources.precedenceOf(PropertySource.named("e")), is(4));
assertThat(sources.precedenceOf(PropertySource.named("f")), is(5));
assertThat(sources.precedenceOf(PropertySource.named("g")), is(6));
assertThat(sources.size()).isEqualTo(7);
assertThat(sources.precedenceOf(PropertySource.named("a"))).isEqualTo(0);
assertThat(sources.precedenceOf(PropertySource.named("b"))).isEqualTo(1);
assertThat(sources.precedenceOf(PropertySource.named("c"))).isEqualTo(2);
assertThat(sources.precedenceOf(PropertySource.named("d"))).isEqualTo(3);
assertThat(sources.precedenceOf(PropertySource.named("e"))).isEqualTo(4);
assertThat(sources.precedenceOf(PropertySource.named("f"))).isEqualTo(5);
assertThat(sources.precedenceOf(PropertySource.named("g"))).isEqualTo(6);
sources.addLast(new MockPropertySource("a"));
assertThat(sources.size(), equalTo(7));
assertThat(sources.precedenceOf(PropertySource.named("b")), is(0));
assertThat(sources.precedenceOf(PropertySource.named("c")), is(1));
assertThat(sources.precedenceOf(PropertySource.named("d")), is(2));
assertThat(sources.precedenceOf(PropertySource.named("e")), is(3));
assertThat(sources.precedenceOf(PropertySource.named("f")), is(4));
assertThat(sources.precedenceOf(PropertySource.named("g")), is(5));
assertThat(sources.precedenceOf(PropertySource.named("a")), is(6));
assertThat(sources.size()).isEqualTo(7);
assertThat(sources.precedenceOf(PropertySource.named("b"))).isEqualTo(0);
assertThat(sources.precedenceOf(PropertySource.named("c"))).isEqualTo(1);
assertThat(sources.precedenceOf(PropertySource.named("d"))).isEqualTo(2);
assertThat(sources.precedenceOf(PropertySource.named("e"))).isEqualTo(3);
assertThat(sources.precedenceOf(PropertySource.named("f"))).isEqualTo(4);
assertThat(sources.precedenceOf(PropertySource.named("g"))).isEqualTo(5);
assertThat(sources.precedenceOf(PropertySource.named("a"))).isEqualTo(6);
sources.addFirst(new MockPropertySource("a"));
assertThat(sources.size(), equalTo(7));
assertThat(sources.precedenceOf(PropertySource.named("a")), is(0));
assertThat(sources.precedenceOf(PropertySource.named("b")), is(1));
assertThat(sources.precedenceOf(PropertySource.named("c")), is(2));
assertThat(sources.precedenceOf(PropertySource.named("d")), is(3));
assertThat(sources.precedenceOf(PropertySource.named("e")), is(4));
assertThat(sources.precedenceOf(PropertySource.named("f")), is(5));
assertThat(sources.precedenceOf(PropertySource.named("g")), is(6));
assertThat(sources.size()).isEqualTo(7);
assertThat(sources.precedenceOf(PropertySource.named("a"))).isEqualTo(0);
assertThat(sources.precedenceOf(PropertySource.named("b"))).isEqualTo(1);
assertThat(sources.precedenceOf(PropertySource.named("c"))).isEqualTo(2);
assertThat(sources.precedenceOf(PropertySource.named("d"))).isEqualTo(3);
assertThat(sources.precedenceOf(PropertySource.named("e"))).isEqualTo(4);
assertThat(sources.precedenceOf(PropertySource.named("f"))).isEqualTo(5);
assertThat(sources.precedenceOf(PropertySource.named("g"))).isEqualTo(6);
assertEquals(sources.remove("a"), PropertySource.named("a"));
assertThat(sources.size(), equalTo(6));
assertThat(sources.contains("a"), is(false));
assertThat(sources.size()).isEqualTo(6);
assertThat(sources.contains("a")).isFalse();
assertNull(sources.remove("a"));
assertThat(sources.size(), equalTo(6));
assertThat(sources.size()).isEqualTo(6);
String bogusPS = "bogus";
assertThatIllegalArgumentException().isThrownBy(() ->
@@ -117,16 +112,16 @@ public class MutablePropertySourcesTests {
.withMessageContaining("does not exist");
sources.addFirst(new MockPropertySource("a"));
assertThat(sources.size(), equalTo(7));
assertThat(sources.precedenceOf(PropertySource.named("a")), is(0));
assertThat(sources.precedenceOf(PropertySource.named("b")), is(1));
assertThat(sources.precedenceOf(PropertySource.named("c")), is(2));
assertThat(sources.size()).isEqualTo(7);
assertThat(sources.precedenceOf(PropertySource.named("a"))).isEqualTo(0);
assertThat(sources.precedenceOf(PropertySource.named("b"))).isEqualTo(1);
assertThat(sources.precedenceOf(PropertySource.named("c"))).isEqualTo(2);
sources.replace("a", new MockPropertySource("a-replaced"));
assertThat(sources.size(), equalTo(7));
assertThat(sources.precedenceOf(PropertySource.named("a-replaced")), is(0));
assertThat(sources.precedenceOf(PropertySource.named("b")), is(1));
assertThat(sources.precedenceOf(PropertySource.named("c")), is(2));
assertThat(sources.size()).isEqualTo(7);
assertThat(sources.precedenceOf(PropertySource.named("a-replaced"))).isEqualTo(0);
assertThat(sources.precedenceOf(PropertySource.named("b"))).isEqualTo(1);
assertThat(sources.precedenceOf(PropertySource.named("c"))).isEqualTo(2);
sources.replace("a-replaced", new MockPropertySource("a"));
@@ -146,7 +141,7 @@ public class MutablePropertySourcesTests {
@Test
public void getNonExistentPropertySourceReturnsNull() {
MutablePropertySources sources = new MutablePropertySources();
assertThat(sources.get("bogus"), nullValue());
assertThat(sources.get("bogus")).isNull();
}
@Test
@@ -175,17 +170,17 @@ public class MutablePropertySourcesTests {
MutablePropertySources sources = new MutablePropertySources();
sources.addLast(new MockPropertySource("test"));
assertThat(sources.stream(), notNullValue());
assertThat(sources.stream().count(), is(1L));
assertThat(sources.stream().anyMatch(source -> "test".equals(source.getName())), is(true));
assertThat(sources.stream().anyMatch(source -> "bogus".equals(source.getName())), is(false));
assertThat(sources.stream()).isNotNull();
assertThat(sources.stream().count()).isEqualTo(1L);
assertThat(sources.stream().anyMatch(source -> "test".equals(source.getName()))).isTrue();
assertThat(sources.stream().anyMatch(source -> "bogus".equals(source.getName()))).isFalse();
}
@Test
public void streamIsEmptyForEmptySources() {
MutablePropertySources sources = new MutablePropertySources();
assertThat(sources.stream(), notNullValue());
assertThat(sources.stream().count(), is(0L));
assertThat(sources.stream()).isNotNull();
assertThat(sources.stream().count()).isEqualTo(0L);
}
}

View File

@@ -24,9 +24,8 @@ import java.util.Properties;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link PropertySource} implementations.
@@ -53,19 +52,19 @@ public class PropertySourceTests {
}};
MapPropertySource mps = new MapPropertySource("mps", map1);
assertThat(mps, equalTo(mps));
assertThat(mps).isEqualTo(mps);
assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("x", map1)), is(true));
assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("x", map2)), is(true));
assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("x", props1)), is(true));
assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("x", props2)), is(true));
assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("x", map1))).isTrue();
assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("x", map2))).isTrue();
assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("x", props1))).isTrue();
assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("x", props2))).isTrue();
assertThat(new MapPropertySource("x", map1).equals(new Object()), is(false));
assertThat(new MapPropertySource("x", map1).equals("x"), is(false));
assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("y", map1)), is(false));
assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("y", map2)), is(false));
assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("y", props1)), is(false));
assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("y", props2)), is(false));
assertThat(new MapPropertySource("x", map1).equals(new Object())).isFalse();
assertThat(new MapPropertySource("x", map1).equals("x")).isFalse();
assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("y", map1))).isFalse();
assertThat(new MapPropertySource("x", map1).equals(new MapPropertySource("y", map2))).isFalse();
assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("y", props1))).isFalse();
assertThat(new MapPropertySource("x", map1).equals(new PropertiesPropertySource("y", props2))).isFalse();
}
@Test
@@ -81,23 +80,23 @@ public class PropertySourceTests {
PropertySource<?> ps1 = new MapPropertySource("ps1", map1);
ps1.getSource();
List<PropertySource<?>> propertySources = new ArrayList<>();
assertThat(propertySources.add(ps1), equalTo(true));
assertThat(propertySources.contains(ps1), is(true));
assertThat(propertySources.contains(PropertySource.named("ps1")), is(true));
assertThat(propertySources.add(ps1)).isEqualTo(true);
assertThat(propertySources.contains(ps1)).isTrue();
assertThat(propertySources.contains(PropertySource.named("ps1"))).isTrue();
PropertySource<?> ps1replacement = new MapPropertySource("ps1", map2); // notice - different map
assertThat(propertySources.add(ps1replacement), is(true)); // true because linkedlist allows duplicates
assertThat(propertySources.size(), is(2));
assertThat(propertySources.remove(PropertySource.named("ps1")), is(true));
assertThat(propertySources.size(), is(1));
assertThat(propertySources.remove(PropertySource.named("ps1")), is(true));
assertThat(propertySources.size(), is(0));
assertThat(propertySources.add(ps1replacement)).isTrue(); // true because linkedlist allows duplicates
assertThat(propertySources).hasSize(2);
assertThat(propertySources.remove(PropertySource.named("ps1"))).isTrue();
assertThat(propertySources).hasSize(1);
assertThat(propertySources.remove(PropertySource.named("ps1"))).isTrue();
assertThat(propertySources).hasSize(0);
PropertySource<?> ps2 = new MapPropertySource("ps2", map2);
propertySources.add(ps1);
propertySources.add(ps2);
assertThat(propertySources.indexOf(PropertySource.named("ps1")), is(0));
assertThat(propertySources.indexOf(PropertySource.named("ps2")), is(1));
assertThat(propertySources.indexOf(PropertySource.named("ps1"))).isEqualTo(0);
assertThat(propertySources.indexOf(PropertySource.named("ps2"))).isEqualTo(1);
propertySources.clear();
}

View File

@@ -26,15 +26,10 @@ import org.junit.Test;
import org.springframework.core.convert.ConverterNotFoundException;
import org.springframework.mock.env.MockPropertySource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.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;
/**
* @author Chris Beams
@@ -60,23 +55,23 @@ public class PropertySourcesPropertyResolverTests {
@Test
public void containsProperty() {
assertThat(propertyResolver.containsProperty("foo"), is(false));
assertThat(propertyResolver.containsProperty("foo")).isFalse();
testProperties.put("foo", "bar");
assertThat(propertyResolver.containsProperty("foo"), is(true));
assertThat(propertyResolver.containsProperty("foo")).isTrue();
}
@Test
public void getProperty() {
assertThat(propertyResolver.getProperty("foo"), nullValue());
assertThat(propertyResolver.getProperty("foo")).isNull();
testProperties.put("foo", "bar");
assertThat(propertyResolver.getProperty("foo"), is("bar"));
assertThat(propertyResolver.getProperty("foo")).isEqualTo("bar");
}
@Test
public void getProperty_withDefaultValue() {
assertThat(propertyResolver.getProperty("foo", "myDefault"), is("myDefault"));
assertThat(propertyResolver.getProperty("foo", "myDefault")).isEqualTo("myDefault");
testProperties.put("foo", "bar");
assertThat(propertyResolver.getProperty("foo"), is("bar"));
assertThat(propertyResolver.getProperty("foo")).isEqualTo("bar");
}
@Test
@@ -84,11 +79,11 @@ public class PropertySourcesPropertyResolverTests {
MutablePropertySources sources = new MutablePropertySources();
PropertyResolver resolver = new PropertySourcesPropertyResolver(sources);
sources.addFirst(new MockPropertySource("ps1").withProperty("pName", "ps1Value"));
assertThat(resolver.getProperty("pName"), equalTo("ps1Value"));
assertThat(resolver.getProperty("pName")).isEqualTo("ps1Value");
sources.addFirst(new MockPropertySource("ps2").withProperty("pName", "ps2Value"));
assertThat(resolver.getProperty("pName"), equalTo("ps2Value"));
assertThat(resolver.getProperty("pName")).isEqualTo("ps2Value");
sources.addFirst(new MockPropertySource("ps3").withProperty("pName", "ps3Value"));
assertThat(resolver.getProperty("pName"), equalTo("ps3Value"));
assertThat(resolver.getProperty("pName")).isEqualTo("ps3Value");
}
@Test
@@ -97,20 +92,20 @@ public class PropertySourcesPropertyResolverTests {
Map<String, Object> nullableProperties = new HashMap<>();
propertySources.addLast(new MapPropertySource("nullableProperties", nullableProperties));
nullableProperties.put("foo", null);
assertThat(propertyResolver.getProperty("foo"), nullValue());
assertThat(propertyResolver.getProperty("foo")).isNull();
}
@Test
public void getProperty_withTargetType_andDefaultValue() {
assertThat(propertyResolver.getProperty("foo", Integer.class, 42), equalTo(42));
assertThat(propertyResolver.getProperty("foo", Integer.class, 42)).isEqualTo(42);
testProperties.put("foo", 13);
assertThat(propertyResolver.getProperty("foo", Integer.class, 42), equalTo(13));
assertThat(propertyResolver.getProperty("foo", Integer.class, 42)).isEqualTo(13);
}
@Test
public void getProperty_withStringArrayConversion() {
testProperties.put("foo", "bar,baz");
assertThat(propertyResolver.getProperty("foo", String[].class), equalTo(new String[] { "bar", "baz" }));
assertThat(propertyResolver.getProperty("foo", String[].class)).isEqualTo(new String[] { "bar", "baz" });
}
@Test
@@ -134,9 +129,9 @@ public class PropertySourcesPropertyResolverTests {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MapPropertySource("testProperties", map));
PropertyResolver propertyResolver = new PropertySourcesPropertyResolver(propertySources);
assertThat(propertyResolver.getProperty(key), equalTo(value1));
assertThat(propertyResolver.getProperty(key)).isEqualTo(value1);
map.put(key, value2); // after construction and first resolution
assertThat(propertyResolver.getProperty(key), equalTo(value2));
assertThat(propertyResolver.getProperty(key)).isEqualTo(value2);
}
@Test
@@ -145,9 +140,9 @@ public class PropertySourcesPropertyResolverTests {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MapPropertySource("testProperties", map));
PropertyResolver propertyResolver = new PropertySourcesPropertyResolver(propertySources);
assertThat(propertyResolver.getProperty("foo"), equalTo(null));
assertThat(propertyResolver.getProperty("foo")).isNull();
map.put("foo", "42");
assertThat(propertyResolver.getProperty("foo"), equalTo("42"));
assertThat(propertyResolver.getProperty("foo")).isEqualTo("42");
}
@Test
@@ -158,21 +153,21 @@ public class PropertySourcesPropertyResolverTests {
propertySources.addLast(new MockPropertySource("system").withProperty("foo", "systemValue"));
// 'local' was added first so has precedence
assertThat(propertyResolver.getProperty("foo"), equalTo("localValue"));
assertThat(propertyResolver.getProperty("foo")).isEqualTo("localValue");
// replace 'local' with new property source
propertySources.replace("local", new MockPropertySource("new").withProperty("foo", "newValue"));
// 'system' now has precedence
assertThat(propertyResolver.getProperty("foo"), equalTo("newValue"));
assertThat(propertyResolver.getProperty("foo")).isEqualTo("newValue");
assertThat(propertySources.size(), is(2));
assertThat(propertySources).hasSize(2);
}
@Test
public void getRequiredProperty() {
testProperties.put("exists", "xyz");
assertThat(propertyResolver.getRequiredProperty("exists"), is("xyz"));
assertThat(propertyResolver.getRequiredProperty("exists")).isEqualTo("xyz");
assertThatIllegalStateException().isThrownBy(() ->
propertyResolver.getRequiredProperty("bogus"));
@@ -181,7 +176,7 @@ public class PropertySourcesPropertyResolverTests {
@Test
public void getRequiredProperty_withStringArrayConversion() {
testProperties.put("exists", "abc,123");
assertThat(propertyResolver.getRequiredProperty("exists", String[].class), equalTo(new String[] { "abc", "123" }));
assertThat(propertyResolver.getRequiredProperty("exists", String[].class)).isEqualTo(new String[] { "abc", "123" });
assertThatIllegalStateException().isThrownBy(() ->
propertyResolver.getRequiredProperty("bogus", String[].class));
@@ -192,7 +187,7 @@ public class PropertySourcesPropertyResolverTests {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MockPropertySource().withProperty("key", "value"));
PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources);
assertThat(resolver.resolvePlaceholders("Replace this ${key}"), equalTo("Replace this value"));
assertThat(resolver.resolvePlaceholders("Replace this ${key}")).isEqualTo("Replace this value");
}
@Test
@@ -200,8 +195,8 @@ public class PropertySourcesPropertyResolverTests {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MockPropertySource().withProperty("key", "value"));
PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources);
assertThat(resolver.resolvePlaceholders("Replace this ${key} plus ${unknown}"),
equalTo("Replace this value plus ${unknown}"));
assertThat(resolver.resolvePlaceholders("Replace this ${key} plus ${unknown}"))
.isEqualTo("Replace this value plus ${unknown}");
}
@Test
@@ -209,8 +204,8 @@ public class PropertySourcesPropertyResolverTests {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MockPropertySource().withProperty("key", "value"));
PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources);
assertThat(resolver.resolvePlaceholders("Replace this ${key} plus ${unknown:defaultValue}"),
equalTo("Replace this value plus defaultValue"));
assertThat(resolver.resolvePlaceholders("Replace this ${key} plus ${unknown:defaultValue}"))
.isEqualTo("Replace this value plus defaultValue");
}
@Test
@@ -224,7 +219,7 @@ public class PropertySourcesPropertyResolverTests {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MockPropertySource().withProperty("key", "value"));
PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources);
assertThat(resolver.resolveRequiredPlaceholders("Replace this ${key}"), equalTo("Replace this value"));
assertThat(resolver.resolveRequiredPlaceholders("Replace this ${key}")).isEqualTo("Replace this value");
}
@Test
@@ -241,8 +236,8 @@ public class PropertySourcesPropertyResolverTests {
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MockPropertySource().withProperty("key", "value"));
PropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources);
assertThat(resolver.resolveRequiredPlaceholders("Replace this ${key} plus ${unknown:defaultValue}"),
equalTo("Replace this value plus defaultValue"));
assertThat(resolver.resolveRequiredPlaceholders("Replace this ${key} plus ${unknown:defaultValue}"))
.isEqualTo("Replace this value plus defaultValue");
}
@Test
@@ -291,24 +286,17 @@ public class PropertySourcesPropertyResolverTests {
.withProperty("pR", "${pL}") // cyclic reference right
);
ConfigurablePropertyResolver pr = new PropertySourcesPropertyResolver(ps);
assertThat(pr.getProperty("p1"), equalTo("v1"));
assertThat(pr.getProperty("p2"), equalTo("v2"));
assertThat(pr.getProperty("p3"), equalTo("v1:v2"));
assertThat(pr.getProperty("p4"), equalTo("v1:v2"));
try {
pr.getProperty("p5");
}
catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(), containsString(
"Could not resolve placeholder 'bogus' in value \"${p1}:${p2}:${bogus}\""));
}
assertThat(pr.getProperty("p6"), equalTo("v1:v2:def"));
try {
pr.getProperty("pL");
}
catch (IllegalArgumentException ex) {
assertTrue(ex.getMessage().toLowerCase().contains("circular"));
}
assertThat(pr.getProperty("p1")).isEqualTo("v1");
assertThat(pr.getProperty("p2")).isEqualTo("v2");
assertThat(pr.getProperty("p3")).isEqualTo("v1:v2");
assertThat(pr.getProperty("p4")).isEqualTo("v1:v2");
assertThatIllegalArgumentException().isThrownBy(() ->
pr.getProperty("p5"))
.withMessageContaining("Could not resolve placeholder 'bogus' in value \"${p1}:${p2}:${bogus}\"");
assertThat(pr.getProperty("p6")).isEqualTo("v1:v2:def");
assertThatIllegalArgumentException().isThrownBy(() ->
pr.getProperty("pL"))
.withMessageContaining("Circular");
}
@Test
@@ -321,35 +309,27 @@ public class PropertySourcesPropertyResolverTests {
.withProperty("p4", "${p1}:${p2}:${bogus}") // unresolvable placeholder
);
ConfigurablePropertyResolver pr = new PropertySourcesPropertyResolver(ps);
assertThat(pr.getProperty("p1"), equalTo("v1"));
assertThat(pr.getProperty("p2"), equalTo("v2"));
assertThat(pr.getProperty("p3"), equalTo("v1:v2:def"));
assertThat(pr.getProperty("p1")).isEqualTo("v1");
assertThat(pr.getProperty("p2")).isEqualTo("v2");
assertThat(pr.getProperty("p3")).isEqualTo("v1:v2:def");
// placeholders nested within the value of "p4" are unresolvable and cause an
// exception by default
try {
pr.getProperty("p4");
}
catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(), containsString(
"Could not resolve placeholder 'bogus' in value \"${p1}:${p2}:${bogus}\""));
}
assertThatIllegalArgumentException().isThrownBy(() ->
pr.getProperty("p4"))
.withMessageContaining("Could not resolve placeholder 'bogus' in value \"${p1}:${p2}:${bogus}\"");
// relax the treatment of unresolvable nested placeholders
pr.setIgnoreUnresolvableNestedPlaceholders(true);
// and observe they now pass through unresolved
assertThat(pr.getProperty("p4"), equalTo("v1:v2:${bogus}"));
assertThat(pr.getProperty("p4")).isEqualTo("v1:v2:${bogus}");
// resolve[Nested]Placeholders methods behave as usual regardless the value of
// ignoreUnresolvableNestedPlaceholders
assertThat(pr.resolvePlaceholders("${p1}:${p2}:${bogus}"), equalTo("v1:v2:${bogus}"));
try {
pr.resolveRequiredPlaceholders("${p1}:${p2}:${bogus}");
}
catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(), containsString(
"Could not resolve placeholder 'bogus' in value \"${p1}:${p2}:${bogus}\""));
}
assertThat(pr.resolvePlaceholders("${p1}:${p2}:${bogus}")).isEqualTo("v1:v2:${bogus}");
assertThatIllegalArgumentException().isThrownBy(() ->
pr.resolveRequiredPlaceholders("${p1}:${p2}:${bogus}"))
.withMessageContaining("Could not resolve placeholder 'bogus' in value \"${p1}:${p2}:${bogus}\"");
}
}

View File

@@ -21,47 +21,45 @@ import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
public class SimpleCommandLineParserTests {
@Test
public void withNoOptions() {
SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser();
assertThat(parser.parse().getOptionValues("foo"), nullValue());
assertThat(parser.parse().getOptionValues("foo")).isNull();
}
@Test
public void withSingleOptionAndNoValue() {
SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser();
CommandLineArgs args = parser.parse("--o1");
assertThat(args.containsOption("o1"), is(true));
assertThat(args.getOptionValues("o1"), equalTo(Collections.EMPTY_LIST));
assertThat(args.containsOption("o1")).isTrue();
assertThat(args.getOptionValues("o1")).isEqualTo(Collections.EMPTY_LIST);
}
@Test
public void withSingleOptionAndValue() {
SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser();
CommandLineArgs args = parser.parse("--o1=v1");
assertThat(args.containsOption("o1"), is(true));
assertThat(args.getOptionValues("o1").get(0), equalTo("v1"));
assertThat(args.containsOption("o1")).isTrue();
assertThat(args.getOptionValues("o1").get(0)).isEqualTo("v1");
}
@Test
public void withMixOfOptionsHavingValueAndOptionsHavingNoValue() {
SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser();
CommandLineArgs args = parser.parse("--o1=v1", "--o2");
assertThat(args.containsOption("o1"), is(true));
assertThat(args.containsOption("o2"), is(true));
assertThat(args.containsOption("o3"), is(false));
assertThat(args.getOptionValues("o1").get(0), equalTo("v1"));
assertThat(args.getOptionValues("o2"), equalTo(Collections.EMPTY_LIST));
assertThat(args.getOptionValues("o3"), nullValue());
assertThat(args.containsOption("o1")).isTrue();
assertThat(args.containsOption("o2")).isTrue();
assertThat(args.containsOption("o3")).isFalse();
assertThat(args.getOptionValues("o1").get(0)).isEqualTo("v1");
assertThat(args.getOptionValues("o2")).isEqualTo(Collections.EMPTY_LIST);
assertThat(args.getOptionValues("o3")).isNull();
}
@Test
@@ -96,13 +94,13 @@ public class SimpleCommandLineParserTests {
public void withNonOptionArguments() {
SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser();
CommandLineArgs args = parser.parse("--o1=v1", "noa1", "--o2=v2", "noa2");
assertThat(args.getOptionValues("o1").get(0), equalTo("v1"));
assertThat(args.getOptionValues("o2").get(0), equalTo("v2"));
assertThat(args.getOptionValues("o1").get(0)).isEqualTo("v1");
assertThat(args.getOptionValues("o2").get(0)).isEqualTo("v2");
List<String> nonOptions = args.getNonOptionArgs();
assertThat(nonOptions.get(0), equalTo("noa1"));
assertThat(nonOptions.get(1), equalTo("noa2"));
assertThat(nonOptions.size(), equalTo(2));
assertThat(nonOptions.get(0)).isEqualTo("noa1");
assertThat(nonOptions.get(1)).isEqualTo("noa2");
assertThat(nonOptions.size()).isEqualTo(2);
}
@Test

View File

@@ -20,10 +20,8 @@ import java.util.List;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link SimpleCommandLinePropertySource}.
@@ -36,46 +34,46 @@ public class SimpleCommandLinePropertySourceTests {
@Test
public void withDefaultName() {
PropertySource<?> ps = new SimpleCommandLinePropertySource();
assertThat(ps.getName(),
equalTo(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME));
assertThat(ps.getName())
.isEqualTo(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME);
}
@Test
public void withCustomName() {
PropertySource<?> ps = new SimpleCommandLinePropertySource("ps1", new String[0]);
assertThat(ps.getName(), equalTo("ps1"));
assertThat(ps.getName()).isEqualTo("ps1");
}
@Test
public void withNoArgs() {
PropertySource<?> ps = new SimpleCommandLinePropertySource();
assertThat(ps.containsProperty("foo"), is(false));
assertThat(ps.getProperty("foo"), nullValue());
assertThat(ps.containsProperty("foo")).isFalse();
assertThat(ps.getProperty("foo")).isNull();
}
@Test
public void withOptionArgsOnly() {
CommandLinePropertySource<?> ps =
new SimpleCommandLinePropertySource("--o1=v1", "--o2");
assertThat(ps.containsProperty("o1"), is(true));
assertThat(ps.containsProperty("o2"), is(true));
assertThat(ps.containsProperty("o3"), is(false));
assertThat(ps.getProperty("o1"), equalTo("v1"));
assertThat(ps.getProperty("o2"), equalTo(""));
assertThat(ps.getProperty("o3"), nullValue());
assertThat(ps.containsProperty("o1")).isTrue();
assertThat(ps.containsProperty("o2")).isTrue();
assertThat(ps.containsProperty("o3")).isFalse();
assertThat(ps.getProperty("o1")).isEqualTo("v1");
assertThat(ps.getProperty("o2")).isEqualTo("");
assertThat(ps.getProperty("o3")).isNull();
}
@Test
public void withDefaultNonOptionArgsNameAndNoNonOptionArgsPresent() {
EnumerablePropertySource<?> ps = new SimpleCommandLinePropertySource("--o1=v1", "--o2");
assertThat(ps.containsProperty("nonOptionArgs"), is(false));
assertThat(ps.containsProperty("o1"), is(true));
assertThat(ps.containsProperty("o2"), is(true));
assertThat(ps.containsProperty("nonOptionArgs")).isFalse();
assertThat(ps.containsProperty("o1")).isTrue();
assertThat(ps.containsProperty("o2")).isTrue();
assertThat(ps.containsProperty("nonOptionArgs"), is(false));
assertThat(ps.getProperty("nonOptionArgs"), nullValue());
assertThat(ps.getPropertyNames().length, is(2));
assertThat(ps.containsProperty("nonOptionArgs")).isFalse();
assertThat(ps.getProperty("nonOptionArgs")).isNull();
assertThat(ps.getPropertyNames().length).isEqualTo(2);
}
@Test
@@ -83,12 +81,12 @@ public class SimpleCommandLinePropertySourceTests {
CommandLinePropertySource<?> ps =
new SimpleCommandLinePropertySource("--o1=v1", "noa1", "--o2", "noa2");
assertThat(ps.containsProperty("nonOptionArgs"), is(true));
assertThat(ps.containsProperty("o1"), is(true));
assertThat(ps.containsProperty("o2"), is(true));
assertThat(ps.containsProperty("nonOptionArgs")).isTrue();
assertThat(ps.containsProperty("o1")).isTrue();
assertThat(ps.containsProperty("o2")).isTrue();
String nonOptionArgs = ps.getProperty("nonOptionArgs");
assertThat(nonOptionArgs, equalTo("noa1,noa2"));
assertThat(nonOptionArgs).isEqualTo("noa1,noa2");
}
@Test
@@ -97,12 +95,12 @@ public class SimpleCommandLinePropertySourceTests {
new SimpleCommandLinePropertySource("--o1=v1", "noa1", "--o2", "noa2");
ps.setNonOptionArgsPropertyName("NOA");
assertThat(ps.containsProperty("nonOptionArgs"), is(false));
assertThat(ps.containsProperty("NOA"), is(true));
assertThat(ps.containsProperty("o1"), is(true));
assertThat(ps.containsProperty("o2"), is(true));
assertThat(ps.containsProperty("nonOptionArgs")).isFalse();
assertThat(ps.containsProperty("NOA")).isTrue();
assertThat(ps.containsProperty("o1")).isTrue();
assertThat(ps.containsProperty("o2")).isTrue();
String nonOptionArgs = ps.getProperty("NOA");
assertThat(nonOptionArgs, equalTo("noa1,noa2"));
assertThat(nonOptionArgs).isEqualTo("noa1,noa2");
}
@Test
@@ -113,16 +111,16 @@ public class SimpleCommandLinePropertySourceTests {
env.getPropertySources().addFirst(ps);
String nonOptionArgs = env.getProperty("nonOptionArgs");
assertThat(nonOptionArgs, equalTo("noa1,noa2"));
assertThat(nonOptionArgs).isEqualTo("noa1,noa2");
String[] nonOptionArgsArray = env.getProperty("nonOptionArgs", String[].class);
assertThat(nonOptionArgsArray[0], equalTo("noa1"));
assertThat(nonOptionArgsArray[1], equalTo("noa2"));
assertThat(nonOptionArgsArray[0]).isEqualTo("noa1");
assertThat(nonOptionArgsArray[1]).isEqualTo("noa2");
@SuppressWarnings("unchecked")
List<String> nonOptionArgsList = env.getProperty("nonOptionArgs", List.class);
assertThat(nonOptionArgsList.get(0), equalTo("noa1"));
assertThat(nonOptionArgsList.get(1), equalTo("noa2"));
assertThat(nonOptionArgsList.get(0)).isEqualTo("noa1");
assertThat(nonOptionArgsList.get(1)).isEqualTo("noa2");
}
}

View File

@@ -28,17 +28,8 @@ import org.junit.Test;
import org.springframework.core.SpringProperties;
import org.springframework.mock.env.MockPropertySource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
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.springframework.core.env.AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME;
@@ -84,64 +75,64 @@ public class StandardEnvironmentTests {
.withProperty("parentKey", "parentVal")
.withProperty("bothKey", "parentBothVal"));
assertThat(child.getProperty("childKey"), is("childVal"));
assertThat(child.getProperty("parentKey"), nullValue());
assertThat(child.getProperty("bothKey"), is("childBothVal"));
assertThat(child.getProperty("childKey")).isEqualTo("childVal");
assertThat(child.getProperty("parentKey")).isNull();
assertThat(child.getProperty("bothKey")).isEqualTo("childBothVal");
assertThat(parent.getProperty("childKey"), nullValue());
assertThat(parent.getProperty("parentKey"), is("parentVal"));
assertThat(parent.getProperty("bothKey"), is("parentBothVal"));
assertThat(parent.getProperty("childKey")).isNull();
assertThat(parent.getProperty("parentKey")).isEqualTo("parentVal");
assertThat(parent.getProperty("bothKey")).isEqualTo("parentBothVal");
assertThat(child.getActiveProfiles(), equalTo(new String[]{"c1","c2"}));
assertThat(parent.getActiveProfiles(), equalTo(new String[]{"p1","p2"}));
assertThat(child.getActiveProfiles()).isEqualTo(new String[]{"c1","c2"});
assertThat(parent.getActiveProfiles()).isEqualTo(new String[]{"p1","p2"});
child.merge(parent);
assertThat(child.getProperty("childKey"), is("childVal"));
assertThat(child.getProperty("parentKey"), is("parentVal"));
assertThat(child.getProperty("bothKey"), is("childBothVal"));
assertThat(child.getProperty("childKey")).isEqualTo("childVal");
assertThat(child.getProperty("parentKey")).isEqualTo("parentVal");
assertThat(child.getProperty("bothKey")).isEqualTo("childBothVal");
assertThat(parent.getProperty("childKey"), nullValue());
assertThat(parent.getProperty("parentKey"), is("parentVal"));
assertThat(parent.getProperty("bothKey"), is("parentBothVal"));
assertThat(parent.getProperty("childKey")).isNull();
assertThat(parent.getProperty("parentKey")).isEqualTo("parentVal");
assertThat(parent.getProperty("bothKey")).isEqualTo("parentBothVal");
assertThat(child.getActiveProfiles(), equalTo(new String[]{"c1","c2","p1","p2"}));
assertThat(parent.getActiveProfiles(), equalTo(new String[]{"p1","p2"}));
assertThat(child.getActiveProfiles()).isEqualTo(new String[]{"c1","c2","p1","p2"});
assertThat(parent.getActiveProfiles()).isEqualTo(new String[]{"p1","p2"});
}
@Test
public void propertySourceOrder() {
ConfigurableEnvironment env = new StandardEnvironment();
MutablePropertySources sources = env.getPropertySources();
assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)), equalTo(0));
assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)), equalTo(1));
assertThat(sources.size(), is(2));
assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME))).isEqualTo(0);
assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME))).isEqualTo(1);
assertThat(sources).hasSize(2);
}
@Test
public void propertySourceTypes() {
ConfigurableEnvironment env = new StandardEnvironment();
MutablePropertySources sources = env.getPropertySources();
assertThat(sources.get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME), instanceOf(SystemEnvironmentPropertySource.class));
assertThat(sources.get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)).isInstanceOf(SystemEnvironmentPropertySource.class);
}
@Test
public void activeProfilesIsEmptyByDefault() {
assertThat(environment.getActiveProfiles().length, is(0));
assertThat(environment.getActiveProfiles().length).isEqualTo(0);
}
@Test
public void defaultProfilesContainsDefaultProfileByDefault() {
assertThat(environment.getDefaultProfiles().length, is(1));
assertThat(environment.getDefaultProfiles()[0], equalTo("default"));
assertThat(environment.getDefaultProfiles().length).isEqualTo(1);
assertThat(environment.getDefaultProfiles()[0]).isEqualTo("default");
}
@Test
public void setActiveProfiles() {
environment.setActiveProfiles("local", "embedded");
String[] activeProfiles = environment.getActiveProfiles();
assertThat(Arrays.asList(activeProfiles), hasItems("local", "embedded"));
assertThat(activeProfiles.length, is(2));
assertThat(activeProfiles).contains("local", "embedded");
assertThat(activeProfiles.length).isEqualTo(2);
}
@Test
@@ -194,36 +185,36 @@ public class StandardEnvironmentTests {
@Test
public void addActiveProfile() {
assertThat(environment.getActiveProfiles().length, is(0));
assertThat(environment.getActiveProfiles().length).isEqualTo(0);
environment.setActiveProfiles("local", "embedded");
assertThat(Arrays.asList(environment.getActiveProfiles()), hasItems("local", "embedded"));
assertThat(environment.getActiveProfiles().length, is(2));
assertThat(environment.getActiveProfiles()).contains("local", "embedded");
assertThat(environment.getActiveProfiles().length).isEqualTo(2);
environment.addActiveProfile("p1");
assertThat(Arrays.asList(environment.getActiveProfiles()), hasItems("p1"));
assertThat(environment.getActiveProfiles().length, is(3));
assertThat(environment.getActiveProfiles()).contains("p1");
assertThat(environment.getActiveProfiles().length).isEqualTo(3);
environment.addActiveProfile("p2");
environment.addActiveProfile("p3");
assertThat(Arrays.asList(environment.getActiveProfiles()), hasItems("p2", "p3"));
assertThat(environment.getActiveProfiles().length, is(5));
assertThat(environment.getActiveProfiles()).contains("p2", "p3");
assertThat(environment.getActiveProfiles().length).isEqualTo(5);
}
@Test
public void addActiveProfile_whenActiveProfilesPropertyIsAlreadySet() {
ConfigurableEnvironment env = new StandardEnvironment();
assertThat(env.getProperty(ACTIVE_PROFILES_PROPERTY_NAME), nullValue());
assertThat(env.getProperty(ACTIVE_PROFILES_PROPERTY_NAME)).isNull();
env.getPropertySources().addFirst(new MockPropertySource().withProperty(ACTIVE_PROFILES_PROPERTY_NAME, "p1"));
assertThat(env.getProperty(ACTIVE_PROFILES_PROPERTY_NAME), equalTo("p1"));
assertThat(env.getProperty(ACTIVE_PROFILES_PROPERTY_NAME)).isEqualTo("p1");
env.addActiveProfile("p2");
assertThat(env.getActiveProfiles(), arrayContaining("p1", "p2"));
assertThat(env.getActiveProfiles()).contains("p1", "p2");
}
@Test
public void reservedDefaultProfile() {
assertThat(environment.getDefaultProfiles(), equalTo(new String[]{RESERVED_DEFAULT_PROFILE_NAME}));
assertThat(environment.getDefaultProfiles()).isEqualTo(new String[]{RESERVED_DEFAULT_PROFILE_NAME});
System.setProperty(DEFAULT_PROFILES_PROPERTY_NAME, "d0");
assertThat(environment.getDefaultProfiles(), equalTo(new String[]{"d0"}));
assertThat(environment.getDefaultProfiles()).isEqualTo(new String[]{"d0"});
environment.setDefaultProfiles("d1", "d2");
assertThat(environment.getDefaultProfiles(), equalTo(new String[]{"d1","d2"}));
assertThat(environment.getDefaultProfiles()).isEqualTo(new String[]{"d1","d2"});
System.getProperties().remove(DEFAULT_PROFILES_PROPERTY_NAME);
}
@@ -241,50 +232,50 @@ public class StandardEnvironmentTests {
@Test
public void getActiveProfiles_systemPropertiesEmpty() {
assertThat(environment.getActiveProfiles().length, is(0));
assertThat(environment.getActiveProfiles().length).isEqualTo(0);
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "");
assertThat(environment.getActiveProfiles().length, is(0));
assertThat(environment.getActiveProfiles().length).isEqualTo(0);
System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME);
}
@Test
public void getActiveProfiles_fromSystemProperties() {
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "foo");
assertThat(Arrays.asList(environment.getActiveProfiles()), hasItem("foo"));
assertThat(Arrays.asList(environment.getActiveProfiles())).contains("foo");
System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME);
}
@Test
public void getActiveProfiles_fromSystemProperties_withMultipleProfiles() {
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "foo,bar");
assertThat(Arrays.asList(environment.getActiveProfiles()), hasItems("foo", "bar"));
assertThat(environment.getActiveProfiles()).contains("foo", "bar");
System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME);
}
@Test
public void getActiveProfiles_fromSystemProperties_withMulitpleProfiles_withWhitespace() {
System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, " bar , baz "); // notice whitespace
assertThat(Arrays.asList(environment.getActiveProfiles()), hasItems("bar", "baz"));
assertThat(environment.getActiveProfiles()).contains("bar", "baz");
System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME);
}
@Test
public void getDefaultProfiles() {
assertThat(environment.getDefaultProfiles(), equalTo(new String[] {RESERVED_DEFAULT_PROFILE_NAME}));
assertThat(environment.getDefaultProfiles()).isEqualTo(new String[] {RESERVED_DEFAULT_PROFILE_NAME});
environment.getPropertySources().addFirst(new MockPropertySource().withProperty(DEFAULT_PROFILES_PROPERTY_NAME, "pd1"));
assertThat(environment.getDefaultProfiles().length, is(1));
assertThat(Arrays.asList(environment.getDefaultProfiles()), hasItem("pd1"));
assertThat(environment.getDefaultProfiles().length).isEqualTo(1);
assertThat(Arrays.asList(environment.getDefaultProfiles())).contains("pd1");
}
@Test
public void setDefaultProfiles() {
environment.setDefaultProfiles();
assertThat(environment.getDefaultProfiles().length, is(0));
assertThat(environment.getDefaultProfiles().length).isEqualTo(0);
environment.setDefaultProfiles("pd1");
assertThat(Arrays.asList(environment.getDefaultProfiles()), hasItem("pd1"));
assertThat(Arrays.asList(environment.getDefaultProfiles())).contains("pd1");
environment.setDefaultProfiles("pd2", "pd3");
assertThat(Arrays.asList(environment.getDefaultProfiles()), not(hasItem("pd1")));
assertThat(Arrays.asList(environment.getDefaultProfiles()), hasItems("pd2", "pd3"));
assertThat(environment.getDefaultProfiles()).doesNotContain("pd1");
assertThat(environment.getDefaultProfiles()).contains("pd2", "pd3");
}
@Test
@@ -313,39 +304,39 @@ public class StandardEnvironmentTests {
@Test
public void acceptsProfiles_activeProfileSetProgrammatically() {
assertThat(environment.acceptsProfiles("p1", "p2"), is(false));
assertThat(environment.acceptsProfiles("p1", "p2")).isFalse();
environment.setActiveProfiles("p1");
assertThat(environment.acceptsProfiles("p1", "p2"), is(true));
assertThat(environment.acceptsProfiles("p1", "p2")).isTrue();
environment.setActiveProfiles("p2");
assertThat(environment.acceptsProfiles("p1", "p2"), is(true));
assertThat(environment.acceptsProfiles("p1", "p2")).isTrue();
environment.setActiveProfiles("p1", "p2");
assertThat(environment.acceptsProfiles("p1", "p2"), is(true));
assertThat(environment.acceptsProfiles("p1", "p2")).isTrue();
}
@Test
public void acceptsProfiles_activeProfileSetViaProperty() {
assertThat(environment.acceptsProfiles("p1"), is(false));
assertThat(environment.acceptsProfiles("p1")).isFalse();
environment.getPropertySources().addFirst(new MockPropertySource().withProperty(ACTIVE_PROFILES_PROPERTY_NAME, "p1"));
assertThat(environment.acceptsProfiles("p1"), is(true));
assertThat(environment.acceptsProfiles("p1")).isTrue();
}
@Test
public void acceptsProfiles_defaultProfile() {
assertThat(environment.acceptsProfiles("pd"), is(false));
assertThat(environment.acceptsProfiles("pd")).isFalse();
environment.setDefaultProfiles("pd");
assertThat(environment.acceptsProfiles("pd"), is(true));
assertThat(environment.acceptsProfiles("pd")).isTrue();
environment.setActiveProfiles("p1");
assertThat(environment.acceptsProfiles("pd"), is(false));
assertThat(environment.acceptsProfiles("p1"), is(true));
assertThat(environment.acceptsProfiles("pd")).isFalse();
assertThat(environment.acceptsProfiles("p1")).isTrue();
}
@Test
public void acceptsProfiles_withNotOperator() {
assertThat(environment.acceptsProfiles("p1"), is(false));
assertThat(environment.acceptsProfiles("!p1"), is(true));
assertThat(environment.acceptsProfiles("p1")).isFalse();
assertThat(environment.acceptsProfiles("!p1")).isTrue();
environment.addActiveProfile("p1");
assertThat(environment.acceptsProfiles("p1"), is(true));
assertThat(environment.acceptsProfiles("!p1"), is(false));
assertThat(environment.acceptsProfiles("p1")).isTrue();
assertThat(environment.acceptsProfiles("!p1")).isFalse();
}
@Test
@@ -356,11 +347,11 @@ public class StandardEnvironmentTests {
@Test
public void acceptsProfiles_withProfileExpression() {
assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2")), is(false));
assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2"))).isFalse();
environment.addActiveProfile("p1");
assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2")), is(false));
assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2"))).isFalse();
environment.addActiveProfile("p2");
assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2")), is(true));
assertThat(environment.acceptsProfiles(Profiles.of("p1 & p2"))).isTrue();
}
@Test
@@ -413,14 +404,14 @@ public class StandardEnvironmentTests {
{
Map<?, ?> systemProperties = environment.getSystemProperties();
assertThat(systemProperties, notNullValue());
assertThat(systemProperties).isNotNull();
assertSame(systemProperties, System.getProperties());
assertThat(systemProperties.get(ALLOWED_PROPERTY_NAME), equalTo((Object)ALLOWED_PROPERTY_VALUE));
assertThat(systemProperties.get(DISALLOWED_PROPERTY_NAME), equalTo((Object)DISALLOWED_PROPERTY_VALUE));
assertThat(systemProperties.get(ALLOWED_PROPERTY_NAME)).isEqualTo(ALLOWED_PROPERTY_VALUE);
assertThat(systemProperties.get(DISALLOWED_PROPERTY_NAME)).isEqualTo(DISALLOWED_PROPERTY_VALUE);
// non-string keys and values work fine... until the security manager is introduced below
assertThat(systemProperties.get(STRING_PROPERTY_NAME), equalTo(NON_STRING_PROPERTY_VALUE));
assertThat(systemProperties.get(NON_STRING_PROPERTY_NAME), equalTo((Object)STRING_PROPERTY_VALUE));
assertThat(systemProperties.get(STRING_PROPERTY_NAME)).isEqualTo(NON_STRING_PROPERTY_VALUE);
assertThat(systemProperties.get(NON_STRING_PROPERTY_NAME)).isEqualTo(STRING_PROPERTY_VALUE);
}
SecurityManager oldSecurityManager = System.getSecurityManager();
@@ -447,17 +438,17 @@ public class StandardEnvironmentTests {
{
Map<?, ?> systemProperties = environment.getSystemProperties();
assertThat(systemProperties, notNullValue());
assertThat(systemProperties, instanceOf(ReadOnlySystemAttributesMap.class));
assertThat((String)systemProperties.get(ALLOWED_PROPERTY_NAME), equalTo(ALLOWED_PROPERTY_VALUE));
assertThat(systemProperties.get(DISALLOWED_PROPERTY_NAME), equalTo(null));
assertThat(systemProperties).isNotNull();
assertThat(systemProperties).isInstanceOf(ReadOnlySystemAttributesMap.class);
assertThat((String)systemProperties.get(ALLOWED_PROPERTY_NAME)).isEqualTo(ALLOWED_PROPERTY_VALUE);
assertThat(systemProperties.get(DISALLOWED_PROPERTY_NAME)).isNull();
// nothing we can do here in terms of warning the user that there was
// actually a (non-string) value available. By this point, we only
// have access to calling System.getProperty(), which itself returns null
// if the value is non-string. So we're stuck with returning a potentially
// misleading null.
assertThat(systemProperties.get(STRING_PROPERTY_NAME), nullValue());
assertThat(systemProperties.get(STRING_PROPERTY_NAME)).isNull();
// in the case of a non-string *key*, however, we can do better. Alert
// the user that under these very special conditions (non-object key +
@@ -481,7 +472,7 @@ public class StandardEnvironmentTests {
{
Map<String, Object> systemEnvironment = environment.getSystemEnvironment();
assertThat(systemEnvironment, notNullValue());
assertThat(systemEnvironment).isNotNull();
assertSame(systemEnvironment, System.getenv());
}
@@ -504,10 +495,10 @@ public class StandardEnvironmentTests {
{
Map<String, Object> systemEnvironment = environment.getSystemEnvironment();
assertThat(systemEnvironment, notNullValue());
assertThat(systemEnvironment, instanceOf(ReadOnlySystemAttributesMap.class));
assertThat(systemEnvironment.get(ALLOWED_PROPERTY_NAME), equalTo((Object)ALLOWED_PROPERTY_VALUE));
assertThat(systemEnvironment.get(DISALLOWED_PROPERTY_NAME), nullValue());
assertThat(systemEnvironment).isNotNull();
assertThat(systemEnvironment).isInstanceOf(ReadOnlySystemAttributesMap.class);
assertThat(systemEnvironment.get(ALLOWED_PROPERTY_NAME)).isEqualTo(ALLOWED_PROPERTY_VALUE);
assertThat(systemEnvironment.get(DISALLOWED_PROPERTY_NAME)).isNull();
}
System.setSecurityManager(oldSecurityManager);

View File

@@ -24,8 +24,8 @@ import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link SystemEnvironmentPropertySource}.
@@ -50,35 +50,35 @@ public class SystemEnvironmentPropertySourceTests {
@Test
public void none() {
assertThat(ps.containsProperty("a.key"), equalTo(false));
assertThat(ps.getProperty("a.key"), equalTo(null));
assertThat(ps.containsProperty("a.key")).isEqualTo(false);
assertThat(ps.getProperty("a.key")).isNull();
}
@Test
public void normalWithoutPeriod() {
envMap.put("akey", "avalue");
assertThat(ps.containsProperty("akey"), equalTo(true));
assertThat(ps.getProperty("akey"), equalTo((Object)"avalue"));
assertThat(ps.containsProperty("akey")).isEqualTo(true);
assertThat(ps.getProperty("akey")).isEqualTo((Object)"avalue");
}
@Test
public void normalWithPeriod() {
envMap.put("a.key", "a.value");
assertThat(ps.containsProperty("a.key"), equalTo(true));
assertThat(ps.getProperty("a.key"), equalTo((Object)"a.value"));
assertThat(ps.containsProperty("a.key")).isEqualTo(true);
assertThat(ps.getProperty("a.key")).isEqualTo((Object)"a.value");
}
@Test
public void withUnderscore() {
envMap.put("a_key", "a_value");
assertThat(ps.containsProperty("a_key"), equalTo(true));
assertThat(ps.containsProperty("a.key"), equalTo(true));
assertThat(ps.containsProperty("a_key")).isEqualTo(true);
assertThat(ps.containsProperty("a.key")).isEqualTo(true);
assertThat(ps.getProperty("a_key"), equalTo((Object)"a_value"));
assertThat( ps.getProperty("a.key"), equalTo((Object)"a_value"));
assertThat(ps.getProperty("a_key")).isEqualTo((Object)"a_value");
assertThat( ps.getProperty("a.key")).isEqualTo((Object)"a_value");
}
@Test
@@ -86,8 +86,8 @@ public class SystemEnvironmentPropertySourceTests {
envMap.put("a_key", "a_value");
envMap.put("a.key", "a.value");
assertThat(ps.getProperty("a_key"), equalTo((Object)"a_value"));
assertThat( ps.getProperty("a.key"), equalTo((Object)"a.value"));
assertThat(ps.getProperty("a_key")).isEqualTo((Object)"a_value");
assertThat( ps.getProperty("a.key")).isEqualTo((Object)"a.value");
}
@Test
@@ -97,55 +97,55 @@ public class SystemEnvironmentPropertySourceTests {
envMap.put("A_DOT.KEY", "a_dot_value");
envMap.put("A_HYPHEN-KEY", "a_hyphen_value");
assertThat(ps.containsProperty("A_KEY"), equalTo(true));
assertThat(ps.containsProperty("A.KEY"), equalTo(true));
assertThat(ps.containsProperty("A-KEY"), equalTo(true));
assertThat(ps.containsProperty("a_key"), equalTo(true));
assertThat(ps.containsProperty("a.key"), equalTo(true));
assertThat(ps.containsProperty("a-key"), equalTo(true));
assertThat(ps.containsProperty("A_LONG_KEY"), equalTo(true));
assertThat(ps.containsProperty("A.LONG.KEY"), equalTo(true));
assertThat(ps.containsProperty("A-LONG-KEY"), equalTo(true));
assertThat(ps.containsProperty("A.LONG-KEY"), equalTo(true));
assertThat(ps.containsProperty("A-LONG.KEY"), equalTo(true));
assertThat(ps.containsProperty("A_long_KEY"), equalTo(true));
assertThat(ps.containsProperty("A.long.KEY"), equalTo(true));
assertThat(ps.containsProperty("A-long-KEY"), equalTo(true));
assertThat(ps.containsProperty("A.long-KEY"), equalTo(true));
assertThat(ps.containsProperty("A-long.KEY"), equalTo(true));
assertThat(ps.containsProperty("A_DOT.KEY"), equalTo(true));
assertThat(ps.containsProperty("A-DOT.KEY"), equalTo(true));
assertThat(ps.containsProperty("A_dot.KEY"), equalTo(true));
assertThat(ps.containsProperty("A-dot.KEY"), equalTo(true));
assertThat(ps.containsProperty("A_HYPHEN-KEY"), equalTo(true));
assertThat(ps.containsProperty("A.HYPHEN-KEY"), equalTo(true));
assertThat(ps.containsProperty("A_hyphen-KEY"), equalTo(true));
assertThat(ps.containsProperty("A.hyphen-KEY"), equalTo(true));
assertThat(ps.containsProperty("A_KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A.KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A-KEY")).isEqualTo(true);
assertThat(ps.containsProperty("a_key")).isEqualTo(true);
assertThat(ps.containsProperty("a.key")).isEqualTo(true);
assertThat(ps.containsProperty("a-key")).isEqualTo(true);
assertThat(ps.containsProperty("A_LONG_KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A.LONG.KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A-LONG-KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A.LONG-KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A-LONG.KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A_long_KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A.long.KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A-long-KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A.long-KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A-long.KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A_DOT.KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A-DOT.KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A_dot.KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A-dot.KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A_HYPHEN-KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A.HYPHEN-KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A_hyphen-KEY")).isEqualTo(true);
assertThat(ps.containsProperty("A.hyphen-KEY")).isEqualTo(true);
assertThat(ps.getProperty("A_KEY"), equalTo("a_value"));
assertThat(ps.getProperty("A.KEY"), equalTo("a_value"));
assertThat(ps.getProperty("A-KEY"), equalTo("a_value"));
assertThat(ps.getProperty("a_key"), equalTo("a_value"));
assertThat(ps.getProperty("a.key"), equalTo("a_value"));
assertThat(ps.getProperty("a-key"), equalTo("a_value"));
assertThat(ps.getProperty("A_LONG_KEY"), equalTo("a_long_value"));
assertThat(ps.getProperty("A.LONG.KEY"), equalTo("a_long_value"));
assertThat(ps.getProperty("A-LONG-KEY"), equalTo("a_long_value"));
assertThat(ps.getProperty("A.LONG-KEY"), equalTo("a_long_value"));
assertThat(ps.getProperty("A-LONG.KEY"), equalTo("a_long_value"));
assertThat(ps.getProperty("A_long_KEY"), equalTo("a_long_value"));
assertThat(ps.getProperty("A.long.KEY"), equalTo("a_long_value"));
assertThat(ps.getProperty("A-long-KEY"), equalTo("a_long_value"));
assertThat(ps.getProperty("A.long-KEY"), equalTo("a_long_value"));
assertThat(ps.getProperty("A-long.KEY"), equalTo("a_long_value"));
assertThat(ps.getProperty("A_DOT.KEY"), equalTo("a_dot_value"));
assertThat(ps.getProperty("A-DOT.KEY"), equalTo("a_dot_value"));
assertThat(ps.getProperty("A_dot.KEY"), equalTo("a_dot_value"));
assertThat(ps.getProperty("A-dot.KEY"), equalTo("a_dot_value"));
assertThat(ps.getProperty("A_HYPHEN-KEY"), equalTo("a_hyphen_value"));
assertThat(ps.getProperty("A.HYPHEN-KEY"), equalTo("a_hyphen_value"));
assertThat(ps.getProperty("A_hyphen-KEY"), equalTo("a_hyphen_value"));
assertThat(ps.getProperty("A.hyphen-KEY"), equalTo("a_hyphen_value"));
assertThat(ps.getProperty("A_KEY")).isEqualTo("a_value");
assertThat(ps.getProperty("A.KEY")).isEqualTo("a_value");
assertThat(ps.getProperty("A-KEY")).isEqualTo("a_value");
assertThat(ps.getProperty("a_key")).isEqualTo("a_value");
assertThat(ps.getProperty("a.key")).isEqualTo("a_value");
assertThat(ps.getProperty("a-key")).isEqualTo("a_value");
assertThat(ps.getProperty("A_LONG_KEY")).isEqualTo("a_long_value");
assertThat(ps.getProperty("A.LONG.KEY")).isEqualTo("a_long_value");
assertThat(ps.getProperty("A-LONG-KEY")).isEqualTo("a_long_value");
assertThat(ps.getProperty("A.LONG-KEY")).isEqualTo("a_long_value");
assertThat(ps.getProperty("A-LONG.KEY")).isEqualTo("a_long_value");
assertThat(ps.getProperty("A_long_KEY")).isEqualTo("a_long_value");
assertThat(ps.getProperty("A.long.KEY")).isEqualTo("a_long_value");
assertThat(ps.getProperty("A-long-KEY")).isEqualTo("a_long_value");
assertThat(ps.getProperty("A.long-KEY")).isEqualTo("a_long_value");
assertThat(ps.getProperty("A-long.KEY")).isEqualTo("a_long_value");
assertThat(ps.getProperty("A_DOT.KEY")).isEqualTo("a_dot_value");
assertThat(ps.getProperty("A-DOT.KEY")).isEqualTo("a_dot_value");
assertThat(ps.getProperty("A_dot.KEY")).isEqualTo("a_dot_value");
assertThat(ps.getProperty("A-dot.KEY")).isEqualTo("a_dot_value");
assertThat(ps.getProperty("A_HYPHEN-KEY")).isEqualTo("a_hyphen_value");
assertThat(ps.getProperty("A.HYPHEN-KEY")).isEqualTo("a_hyphen_value");
assertThat(ps.getProperty("A_hyphen-KEY")).isEqualTo("a_hyphen_value");
assertThat(ps.getProperty("A.hyphen-KEY")).isEqualTo("a_hyphen_value");
}
@Test
@@ -170,8 +170,8 @@ public class SystemEnvironmentPropertySourceTests {
}
};
assertThat(ps.containsProperty("A_KEY"), equalTo(true));
assertThat(ps.getProperty("A_KEY"), equalTo((Object)"a_value"));
assertThat(ps.containsProperty("A_KEY")).isEqualTo(true);
assertThat(ps.getProperty("A_KEY")).isEqualTo((Object)"a_value");
}
}

View File

@@ -28,19 +28,15 @@ import java.nio.file.AccessDeniedException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.springframework.util.FileCopyUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -101,75 +97,75 @@ public class PathResourceTests {
public void createFromPath() {
Path path = Paths.get(TEST_FILE);
PathResource resource = new PathResource(path);
assertThat(resource.getPath(), equalTo(TEST_FILE));
assertThat(resource.getPath()).isEqualTo(TEST_FILE);
}
@Test
public void createFromString() {
PathResource resource = new PathResource(TEST_FILE);
assertThat(resource.getPath(), equalTo(TEST_FILE));
assertThat(resource.getPath()).isEqualTo(TEST_FILE);
}
@Test
public void createFromUri() {
File file = new File(TEST_FILE);
PathResource resource = new PathResource(file.toURI());
assertThat(resource.getPath(), equalTo(file.getAbsoluteFile().toString()));
assertThat(resource.getPath()).isEqualTo(file.getAbsoluteFile().toString());
}
@Test
public void getPathForFile() {
PathResource resource = new PathResource(TEST_FILE);
assertThat(resource.getPath(), equalTo(TEST_FILE));
assertThat(resource.getPath()).isEqualTo(TEST_FILE);
}
@Test
public void getPathForDir() {
PathResource resource = new PathResource(TEST_DIR);
assertThat(resource.getPath(), equalTo(TEST_DIR));
assertThat(resource.getPath()).isEqualTo(TEST_DIR);
}
@Test
public void fileExists() {
PathResource resource = new PathResource(TEST_FILE);
assertThat(resource.exists(), equalTo(true));
assertThat(resource.exists()).isEqualTo(true);
}
@Test
public void dirExists() {
PathResource resource = new PathResource(TEST_DIR);
assertThat(resource.exists(), equalTo(true));
assertThat(resource.exists()).isEqualTo(true);
}
@Test
public void fileDoesNotExist() {
PathResource resource = new PathResource(NON_EXISTING_FILE);
assertThat(resource.exists(), equalTo(false));
assertThat(resource.exists()).isEqualTo(false);
}
@Test
public void fileIsReadable() {
PathResource resource = new PathResource(TEST_FILE);
assertThat(resource.isReadable(), equalTo(true));
assertThat(resource.isReadable()).isEqualTo(true);
}
@Test
public void doesNotExistIsNotReadable() {
PathResource resource = new PathResource(NON_EXISTING_FILE);
assertThat(resource.isReadable(), equalTo(false));
assertThat(resource.isReadable()).isEqualTo(false);
}
@Test
public void directoryIsNotReadable() {
PathResource resource = new PathResource(TEST_DIR);
assertThat(resource.isReadable(), equalTo(false));
assertThat(resource.isReadable()).isEqualTo(false);
}
@Test
public void getInputStream() throws IOException {
PathResource resource = new PathResource(TEST_FILE);
byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
assertThat(bytes.length, greaterThan(0));
assertThat(bytes.length).isGreaterThan(0);
}
@Test
@@ -189,20 +185,20 @@ public class PathResourceTests {
@Test
public void getUrl() throws IOException {
PathResource resource = new PathResource(TEST_FILE);
assertThat(resource.getURL().toString(), Matchers.endsWith("core/io/example.properties"));
assertThat(resource.getURL().toString()).endsWith("core/io/example.properties");
}
@Test
public void getUri() throws IOException {
PathResource resource = new PathResource(TEST_FILE);
assertThat(resource.getURI().toString(), Matchers.endsWith("core/io/example.properties"));
assertThat(resource.getURI().toString()).endsWith("core/io/example.properties");
}
@Test
public void getFile() throws IOException {
PathResource resource = new PathResource(TEST_FILE);
File file = new File(TEST_FILE);
assertThat(resource.getFile().getAbsoluteFile(), equalTo(file.getAbsoluteFile()));
assertThat(resource.getFile().getAbsoluteFile()).isEqualTo(file.getAbsoluteFile());
}
@Test
@@ -219,65 +215,65 @@ public class PathResourceTests {
public void contentLength() throws IOException {
PathResource resource = new PathResource(TEST_FILE);
File file = new File(TEST_FILE);
assertThat(resource.contentLength(), equalTo(file.length()));
assertThat(resource.contentLength()).isEqualTo(file.length());
}
@Test
public void contentLengthForDirectory() throws IOException {
PathResource resource = new PathResource(TEST_DIR);
File file = new File(TEST_DIR);
assertThat(resource.contentLength(), equalTo(file.length()));
assertThat(resource.contentLength()).isEqualTo(file.length());
}
@Test
public void lastModified() throws IOException {
PathResource resource = new PathResource(TEST_FILE);
File file = new File(TEST_FILE);
assertThat(resource.lastModified() / 1000, equalTo(file.lastModified() / 1000));
assertThat(resource.lastModified() / 1000).isEqualTo(file.lastModified() / 1000);
}
@Test
public void createRelativeFromDir() throws IOException {
Resource resource = new PathResource(TEST_DIR).createRelative("example.properties");
assertThat(resource, equalTo((Resource) new PathResource(TEST_FILE)));
assertThat(resource).isEqualTo(new PathResource(TEST_FILE));
}
@Test
public void createRelativeFromFile() throws IOException {
Resource resource = new PathResource(TEST_FILE).createRelative("../example.properties");
assertThat(resource, equalTo((Resource) new PathResource(TEST_FILE)));
assertThat(resource).isEqualTo(new PathResource(TEST_FILE));
}
@Test
public void filename() {
Resource resource = new PathResource(TEST_FILE);
assertThat(resource.getFilename(), equalTo("example.properties"));
assertThat(resource.getFilename()).isEqualTo("example.properties");
}
@Test
public void description() {
Resource resource = new PathResource(TEST_FILE);
assertThat(resource.getDescription(), containsString("path ["));
assertThat(resource.getDescription(), containsString(TEST_FILE));
assertThat(resource.getDescription()).contains("path [");
assertThat(resource.getDescription()).contains(TEST_FILE);
}
@Test
public void fileIsWritable() {
PathResource resource = new PathResource(TEST_FILE);
assertThat(resource.isWritable(), equalTo(true));
assertThat(resource.isWritable()).isEqualTo(true);
}
@Test
public void directoryIsNotWritable() {
PathResource resource = new PathResource(TEST_DIR);
assertThat(resource.isWritable(), equalTo(false));
assertThat(resource.isWritable()).isEqualTo(false);
}
@Test
public void outputStream() throws IOException {
PathResource resource = new PathResource(temporaryFolder.newFile("test").toPath());
FileCopyUtils.copy("test".getBytes(StandardCharsets.UTF_8), resource.getOutputStream());
assertThat(resource.contentLength(), equalTo(4L));
assertThat(resource.contentLength()).isEqualTo(4L);
}
@Test
@@ -286,7 +282,7 @@ public class PathResourceTests {
file.delete();
PathResource resource = new PathResource(file.toPath());
FileCopyUtils.copy("test".getBytes(), resource.getOutputStream());
assertThat(resource.contentLength(), equalTo(4L));
assertThat(resource.contentLength()).isEqualTo(4L);
}
@Test
@@ -305,7 +301,7 @@ public class PathResourceTests {
ByteBuffer buffer = ByteBuffer.allocate((int) resource.contentLength());
channel.read(buffer);
buffer.rewind();
assertThat(buffer.limit(), greaterThan(0));
assertThat(buffer.limit()).isGreaterThan(0);
}
finally {
if (channel != null) {
@@ -346,7 +342,7 @@ public class PathResourceTests {
channel.close();
}
}
assertThat(resource.contentLength(), equalTo(4L));
assertThat(resource.contentLength()).isEqualTo(4L);
}
}

View File

@@ -32,10 +32,8 @@ import org.junit.Test;
import org.springframework.util.FileCopyUtils;
import static org.assertj.core.api.Assertions.assertThat;
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;
@@ -255,7 +253,7 @@ public class ResourceTests {
resource.createRelative("/testing"))
.withMessageContaining(name);
assertThat(resource.getFilename(), nullValue());
assertThat(resource.getFilename()).isNull();
}
@Test
@@ -270,7 +268,7 @@ public class ResourceTests {
return "";
}
};
assertThat(resource.contentLength(), is(3L));
assertThat(resource.contentLength()).isEqualTo(3L);
}
@Test

View File

@@ -24,8 +24,7 @@ import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
/**
@@ -49,49 +48,49 @@ public class ResourcePropertySourceTests {
public void withLocationAndGeneratedName() throws IOException {
PropertySource<?> ps = new ResourcePropertySource(PROPERTIES_LOCATION);
assertEquals("bar", ps.getProperty("foo"));
assertThat(ps.getName(), is(PROPERTIES_RESOURCE_DESCRIPTION));
assertThat(ps.getName()).isEqualTo(PROPERTIES_RESOURCE_DESCRIPTION);
}
@Test
public void xmlWithLocationAndGeneratedName() throws IOException {
PropertySource<?> ps = new ResourcePropertySource(XML_PROPERTIES_LOCATION);
assertEquals("bar", ps.getProperty("foo"));
assertThat(ps.getName(), is(XML_PROPERTIES_RESOURCE_DESCRIPTION));
assertThat(ps.getName()).isEqualTo(XML_PROPERTIES_RESOURCE_DESCRIPTION);
}
@Test
public void withLocationAndExplicitName() throws IOException {
PropertySource<?> ps = new ResourcePropertySource("ps1", PROPERTIES_LOCATION);
assertEquals("bar", ps.getProperty("foo"));
assertThat(ps.getName(), is("ps1"));
assertThat(ps.getName()).isEqualTo("ps1");
}
@Test
public void withLocationAndExplicitNameAndExplicitClassLoader() throws IOException {
PropertySource<?> ps = new ResourcePropertySource("ps1", PROPERTIES_LOCATION, getClass().getClassLoader());
assertEquals("bar", ps.getProperty("foo"));
assertThat(ps.getName(), is("ps1"));
assertThat(ps.getName()).isEqualTo("ps1");
}
@Test
public void withLocationAndGeneratedNameAndExplicitClassLoader() throws IOException {
PropertySource<?> ps = new ResourcePropertySource(PROPERTIES_LOCATION, getClass().getClassLoader());
assertEquals("bar", ps.getProperty("foo"));
assertThat(ps.getName(), is(PROPERTIES_RESOURCE_DESCRIPTION));
assertThat(ps.getName()).isEqualTo(PROPERTIES_RESOURCE_DESCRIPTION);
}
@Test
public void withResourceAndGeneratedName() throws IOException {
PropertySource<?> ps = new ResourcePropertySource(new ClassPathResource(PROPERTIES_PATH));
assertEquals("bar", ps.getProperty("foo"));
assertThat(ps.getName(), is(PROPERTIES_RESOURCE_DESCRIPTION));
assertThat(ps.getName()).isEqualTo(PROPERTIES_RESOURCE_DESCRIPTION);
}
@Test
public void withResourceAndExplicitName() throws IOException {
PropertySource<?> ps = new ResourcePropertySource("ps1", new ClassPathResource(PROPERTIES_PATH));
assertEquals("bar", ps.getProperty("foo"));
assertThat(ps.getName(), is("ps1"));
assertThat(ps.getName()).isEqualTo("ps1");
}
@Test

View File

@@ -22,10 +22,9 @@ import org.junit.Test;
import org.springframework.util.ConcurrencyThrottleSupport;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -59,7 +58,7 @@ public class SimpleAsyncTaskExecutorTests {
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor(customPrefix);
ThreadNameHarvester task = new ThreadNameHarvester(monitor);
executeAndWait(executor, task, monitor);
assertThat(task.getThreadName(), startsWith(customPrefix));
assertThat(task.getThreadName()).startsWith(customPrefix);
}
@Test

View File

@@ -18,8 +18,8 @@ package org.springframework.core.type;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Abstract base class for testing implementations of
@@ -36,7 +36,7 @@ public abstract class AbstractClassMetadataMemberClassTests {
public void withNoMemberClasses() {
ClassMetadata metadata = getClassMetadataFor(L0_a.class);
String[] nestedClasses = metadata.getMemberClassNames();
assertThat(nestedClasses, equalTo(new String[]{}));
assertThat(nestedClasses).isEqualTo(new String[]{});
}
public static class L0_a {
@@ -47,7 +47,7 @@ public abstract class AbstractClassMetadataMemberClassTests {
public void withPublicMemberClasses() {
ClassMetadata metadata = getClassMetadataFor(L0_b.class);
String[] nestedClasses = metadata.getMemberClassNames();
assertThat(nestedClasses, equalTo(new String[]{L0_b.L1.class.getName()}));
assertThat(nestedClasses).isEqualTo(new String[]{L0_b.L1.class.getName()});
}
public static class L0_b {
@@ -59,7 +59,7 @@ public abstract class AbstractClassMetadataMemberClassTests {
public void withNonPublicMemberClasses() {
ClassMetadata metadata = getClassMetadataFor(L0_c.class);
String[] nestedClasses = metadata.getMemberClassNames();
assertThat(nestedClasses, equalTo(new String[]{L0_c.L1.class.getName()}));
assertThat(nestedClasses).isEqualTo(new String[]{L0_c.L1.class.getName()});
}
public static class L0_c {
@@ -71,7 +71,7 @@ public abstract class AbstractClassMetadataMemberClassTests {
public void againstMemberClass() {
ClassMetadata metadata = getClassMetadataFor(L0_b.L1.class);
String[] nestedClasses = metadata.getMemberClassNames();
assertThat(nestedClasses, equalTo(new String[]{}));
assertThat(nestedClasses).isEqualTo(new String[]{});
}
}

View File

@@ -38,11 +38,7 @@ import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import org.springframework.stereotype.Component;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -90,25 +86,25 @@ public class AnnotationMetadataTests {
}
private void doTestSubClassAnnotationInfo(AnnotationMetadata metadata) {
assertThat(metadata.getClassName(), is(AnnotatedComponentSubClass.class.getName()));
assertThat(metadata.isInterface(), is(false));
assertThat(metadata.isAnnotation(), is(false));
assertThat(metadata.isAbstract(), is(false));
assertThat(metadata.isConcrete(), is(true));
assertThat(metadata.hasSuperClass(), is(true));
assertThat(metadata.getSuperClassName(), is(AnnotatedComponent.class.getName()));
assertThat(metadata.getInterfaceNames().length, is(0));
assertThat(metadata.isAnnotated(Component.class.getName()), is(false));
assertThat(metadata.isAnnotated(Scope.class.getName()), is(false));
assertThat(metadata.isAnnotated(SpecialAttr.class.getName()), is(false));
assertThat(metadata.hasAnnotation(Component.class.getName()), is(false));
assertThat(metadata.hasAnnotation(Scope.class.getName()), is(false));
assertThat(metadata.hasAnnotation(SpecialAttr.class.getName()), is(false));
assertThat(metadata.getAnnotationTypes().size(), is(0));
assertThat(metadata.getAnnotationAttributes(Component.class.getName()), nullValue());
assertThat(metadata.getAnnotatedMethods(DirectAnnotation.class.getName()).size(), equalTo(0));
assertThat(metadata.isAnnotated(IsAnnotatedAnnotation.class.getName()), equalTo(false));
assertThat(metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()), nullValue());
assertThat(metadata.getClassName()).isEqualTo(AnnotatedComponentSubClass.class.getName());
assertThat(metadata.isInterface()).isFalse();
assertThat(metadata.isAnnotation()).isFalse();
assertThat(metadata.isAbstract()).isFalse();
assertThat(metadata.isConcrete()).isTrue();
assertThat(metadata.hasSuperClass()).isTrue();
assertThat(metadata.getSuperClassName()).isEqualTo(AnnotatedComponent.class.getName());
assertThat(metadata.getInterfaceNames().length).isEqualTo(0);
assertThat(metadata.isAnnotated(Component.class.getName())).isFalse();
assertThat(metadata.isAnnotated(Scope.class.getName())).isFalse();
assertThat(metadata.isAnnotated(SpecialAttr.class.getName())).isFalse();
assertThat(metadata.hasAnnotation(Component.class.getName())).isFalse();
assertThat(metadata.hasAnnotation(Scope.class.getName())).isFalse();
assertThat(metadata.hasAnnotation(SpecialAttr.class.getName())).isFalse();
assertThat(metadata.getAnnotationTypes()).hasSize(0);
assertThat(metadata.getAnnotationAttributes(Component.class.getName())).isNull();
assertThat(metadata.getAnnotatedMethods(DirectAnnotation.class.getName()).size()).isEqualTo(0);
assertThat(metadata.isAnnotated(IsAnnotatedAnnotation.class.getName())).isEqualTo(false);
assertThat(metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName())).isNull();
}
@Test
@@ -126,17 +122,17 @@ public class AnnotationMetadataTests {
}
private void doTestMetadataForInterfaceClass(AnnotationMetadata metadata) {
assertThat(metadata.getClassName(), is(AnnotationMetadata.class.getName()));
assertThat(metadata.isInterface(), is(true));
assertThat(metadata.isAnnotation(), is(false));
assertThat(metadata.isAbstract(), is(true));
assertThat(metadata.isConcrete(), is(false));
assertThat(metadata.hasSuperClass(), is(false));
assertThat(metadata.getSuperClassName(), nullValue());
assertThat(metadata.getInterfaceNames().length, is(2));
assertThat(metadata.getInterfaceNames()[0], is(ClassMetadata.class.getName()));
assertThat(metadata.getInterfaceNames()[1], is(AnnotatedTypeMetadata.class.getName()));
assertThat(metadata.getAnnotationTypes().size(), is(0));
assertThat(metadata.getClassName()).isEqualTo(AnnotationMetadata.class.getName());
assertThat(metadata.isInterface()).isTrue();
assertThat(metadata.isAnnotation()).isFalse();
assertThat(metadata.isAbstract()).isTrue();
assertThat(metadata.isConcrete()).isFalse();
assertThat(metadata.hasSuperClass()).isFalse();
assertThat(metadata.getSuperClassName()).isNull();
assertThat(metadata.getInterfaceNames().length).isEqualTo(2);
assertThat(metadata.getInterfaceNames()[0]).isEqualTo(ClassMetadata.class.getName());
assertThat(metadata.getInterfaceNames()[1]).isEqualTo(AnnotatedTypeMetadata.class.getName());
assertThat(metadata.getAnnotationTypes()).hasSize(0);
}
@Test
@@ -154,22 +150,22 @@ public class AnnotationMetadataTests {
}
private void doTestMetadataForAnnotationClass(AnnotationMetadata metadata) {
assertThat(metadata.getClassName(), is(Component.class.getName()));
assertThat(metadata.isInterface(), is(true));
assertThat(metadata.isAnnotation(), is(true));
assertThat(metadata.isAbstract(), is(true));
assertThat(metadata.isConcrete(), is(false));
assertThat(metadata.hasSuperClass(), is(false));
assertThat(metadata.getSuperClassName(), nullValue());
assertThat(metadata.getInterfaceNames().length, is(1));
assertThat(metadata.getInterfaceNames()[0], is(Annotation.class.getName()));
assertThat(metadata.isAnnotated(Documented.class.getName()), is(false));
assertThat(metadata.isAnnotated(Scope.class.getName()), is(false));
assertThat(metadata.isAnnotated(SpecialAttr.class.getName()), is(false));
assertThat(metadata.hasAnnotation(Documented.class.getName()), is(false));
assertThat(metadata.hasAnnotation(Scope.class.getName()), is(false));
assertThat(metadata.hasAnnotation(SpecialAttr.class.getName()), is(false));
assertThat(metadata.getAnnotationTypes().size(), is(1));
assertThat(metadata.getClassName()).isEqualTo(Component.class.getName());
assertThat(metadata.isInterface()).isTrue();
assertThat(metadata.isAnnotation()).isTrue();
assertThat(metadata.isAbstract()).isTrue();
assertThat(metadata.isConcrete()).isFalse();
assertThat(metadata.hasSuperClass()).isFalse();
assertThat(metadata.getSuperClassName()).isNull();
assertThat(metadata.getInterfaceNames().length).isEqualTo(1);
assertThat(metadata.getInterfaceNames()[0]).isEqualTo(Annotation.class.getName());
assertThat(metadata.isAnnotated(Documented.class.getName())).isFalse();
assertThat(metadata.isAnnotated(Scope.class.getName())).isFalse();
assertThat(metadata.isAnnotated(SpecialAttr.class.getName())).isFalse();
assertThat(metadata.hasAnnotation(Documented.class.getName())).isFalse();
assertThat(metadata.hasAnnotation(Scope.class.getName())).isFalse();
assertThat(metadata.hasAnnotation(SpecialAttr.class.getName())).isFalse();
assertThat(metadata.getAnnotationTypes()).hasSize(1);
}
/**
@@ -185,7 +181,7 @@ public class AnnotationMetadataTests {
AnnotationMetadata metadata = new StandardAnnotationMetadata(AnnotatedComponent.class);
AnnotationAttributes specialAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(SpecialAttr.class.getName());
Annotation[] nestedAnnoArray = (Annotation[]) specialAttrs.get("nestedAnnoArray");
assertThat(nestedAnnoArray[0], instanceOf(NestedAnno.class));
assertThat(nestedAnnoArray[0]).isInstanceOf(NestedAnno.class);
}
@Test
@@ -206,13 +202,9 @@ public class AnnotationMetadataTests {
private void assertMetaAnnotationOverrides(AnnotationMetadata metadata) {
AnnotationAttributes attributes = (AnnotationAttributes) metadata.getAnnotationAttributes(
TestComponentScan.class.getName(), false);
String[] basePackages = attributes.getStringArray("basePackages");
assertThat("length of basePackages[]", basePackages.length, is(1));
assertThat("basePackages[0]", basePackages[0], is("org.example.componentscan"));
String[] value = attributes.getStringArray("value");
assertThat("length of value[]", value.length, is(0));
Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses");
assertThat("length of basePackageClasses[]", basePackageClasses.length, is(0));
assertThat(attributes.getStringArray("basePackages")).containsExactly("org.example.componentscan");
assertThat(attributes.getStringArray("value")).isEmpty();
assertThat(attributes.getClassArray("basePackageClasses")).isEmpty();
}
@Test // SPR-11649
@@ -262,104 +254,104 @@ public class AnnotationMetadataTests {
AnnotationAttributes attributes1 = (AnnotationAttributes) metadata.getAnnotationAttributes(
NamedAnnotation1.class.getName(), false);
String name1 = attributes1.getString("name");
assertThat("name of NamedAnnotation1", name1, is("name 1"));
assertThat(name1).as("name of NamedAnnotation1").isEqualTo("name 1");
AnnotationAttributes attributes2 = (AnnotationAttributes) metadata.getAnnotationAttributes(
NamedAnnotation2.class.getName(), false);
String name2 = attributes2.getString("name");
assertThat("name of NamedAnnotation2", name2, is("name 2"));
assertThat(name2).as("name of NamedAnnotation2").isEqualTo("name 2");
AnnotationAttributes attributes3 = (AnnotationAttributes) metadata.getAnnotationAttributes(
NamedAnnotation3.class.getName(), false);
String name3 = attributes3.getString("name");
assertThat("name of NamedAnnotation3", name3, is("name 3"));
assertThat(name3).as("name of NamedAnnotation3").isEqualTo("name 3");
}
private void doTestAnnotationInfo(AnnotationMetadata metadata) {
assertThat(metadata.getClassName(), is(AnnotatedComponent.class.getName()));
assertThat(metadata.isInterface(), is(false));
assertThat(metadata.isAnnotation(), is(false));
assertThat(metadata.isAbstract(), is(false));
assertThat(metadata.isConcrete(), is(true));
assertThat(metadata.hasSuperClass(), is(true));
assertThat(metadata.getSuperClassName(), is(Object.class.getName()));
assertThat(metadata.getInterfaceNames().length, is(1));
assertThat(metadata.getInterfaceNames()[0], is(Serializable.class.getName()));
assertThat(metadata.getClassName()).isEqualTo(AnnotatedComponent.class.getName());
assertThat(metadata.isInterface()).isFalse();
assertThat(metadata.isAnnotation()).isFalse();
assertThat(metadata.isAbstract()).isFalse();
assertThat(metadata.isConcrete()).isTrue();
assertThat(metadata.hasSuperClass()).isTrue();
assertThat(metadata.getSuperClassName()).isEqualTo(Object.class.getName());
assertThat(metadata.getInterfaceNames().length).isEqualTo(1);
assertThat(metadata.getInterfaceNames()[0]).isEqualTo(Serializable.class.getName());
assertThat(metadata.hasAnnotation(Component.class.getName()), is(true));
assertThat(metadata.hasAnnotation(Scope.class.getName()), is(true));
assertThat(metadata.hasAnnotation(SpecialAttr.class.getName()), is(true));
assertThat(metadata.getAnnotationTypes().size(), is(6));
assertThat(metadata.getAnnotationTypes().contains(Component.class.getName()), is(true));
assertThat(metadata.getAnnotationTypes().contains(Scope.class.getName()), is(true));
assertThat(metadata.getAnnotationTypes().contains(SpecialAttr.class.getName()), is(true));
assertThat(metadata.hasAnnotation(Component.class.getName())).isTrue();
assertThat(metadata.hasAnnotation(Scope.class.getName())).isTrue();
assertThat(metadata.hasAnnotation(SpecialAttr.class.getName())).isTrue();
assertThat(metadata.getAnnotationTypes()).hasSize(6);
assertThat(metadata.getAnnotationTypes().contains(Component.class.getName())).isTrue();
assertThat(metadata.getAnnotationTypes().contains(Scope.class.getName())).isTrue();
assertThat(metadata.getAnnotationTypes().contains(SpecialAttr.class.getName())).isTrue();
AnnotationAttributes compAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(Component.class.getName());
assertThat(compAttrs.size(), is(1));
assertThat(compAttrs.getString("value"), is("myName"));
assertThat(compAttrs).hasSize(1);
assertThat(compAttrs.getString("value")).isEqualTo("myName");
AnnotationAttributes scopeAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(Scope.class.getName());
assertThat(scopeAttrs.size(), is(1));
assertThat(scopeAttrs.getString("value"), is("myScope"));
assertThat(scopeAttrs).hasSize(1);
assertThat(scopeAttrs.getString("value")).isEqualTo("myScope");
Set<MethodMetadata> methods = metadata.getAnnotatedMethods(DirectAnnotation.class.getName());
MethodMetadata method = methods.iterator().next();
assertEquals("direct", method.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value"));
assertEquals("direct", method.getAnnotationAttributes(DirectAnnotation.class.getName()).get("myValue"));
List<Object> allMeta = method.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("value");
assertThat(new HashSet<>(allMeta), is(equalTo(new HashSet<Object>(Arrays.asList("direct", "meta")))));
assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet<Object>(Arrays.asList("direct", "meta")));
allMeta = method.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("additional");
assertThat(new HashSet<>(allMeta), is(equalTo(new HashSet<Object>(Arrays.asList("direct")))));
assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet<Object>(Arrays.asList("direct")));
assertTrue(metadata.isAnnotated(IsAnnotatedAnnotation.class.getName()));
{ // perform tests with classValuesAsString = false (the default)
AnnotationAttributes specialAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(SpecialAttr.class.getName());
assertThat(specialAttrs.size(), is(6));
assertThat(specialAttrs).hasSize(6);
assertTrue(String.class.isAssignableFrom(specialAttrs.getClass("clazz")));
assertTrue(specialAttrs.getEnum("state").equals(Thread.State.NEW));
AnnotationAttributes nestedAnno = specialAttrs.getAnnotation("nestedAnno");
assertThat("na", is(nestedAnno.getString("value")));
assertThat("na").isEqualTo(nestedAnno.getString("value"));
assertTrue(nestedAnno.getEnum("anEnum").equals(SomeEnum.LABEL1));
assertArrayEquals(new Class<?>[] {String.class}, (Class<?>[]) nestedAnno.get("classArray"));
AnnotationAttributes[] nestedAnnoArray = specialAttrs.getAnnotationArray("nestedAnnoArray");
assertThat(nestedAnnoArray.length, is(2));
assertThat(nestedAnnoArray[0].getString("value"), is("default"));
assertThat(nestedAnnoArray.length).isEqualTo(2);
assertThat(nestedAnnoArray[0].getString("value")).isEqualTo("default");
assertTrue(nestedAnnoArray[0].getEnum("anEnum").equals(SomeEnum.DEFAULT));
assertArrayEquals(new Class<?>[] {Void.class}, (Class<?>[]) nestedAnnoArray[0].get("classArray"));
assertThat(nestedAnnoArray[1].getString("value"), is("na1"));
assertThat(nestedAnnoArray[1].getString("value")).isEqualTo("na1");
assertTrue(nestedAnnoArray[1].getEnum("anEnum").equals(SomeEnum.LABEL2));
assertArrayEquals(new Class<?>[] {Number.class}, (Class<?>[]) nestedAnnoArray[1].get("classArray"));
assertArrayEquals(new Class<?>[] {Number.class}, nestedAnnoArray[1].getClassArray("classArray"));
AnnotationAttributes optional = specialAttrs.getAnnotation("optional");
assertThat(optional.getString("value"), is("optional"));
assertThat(optional.getString("value")).isEqualTo("optional");
assertTrue(optional.getEnum("anEnum").equals(SomeEnum.DEFAULT));
assertArrayEquals(new Class<?>[] {Void.class}, (Class<?>[]) optional.get("classArray"));
assertArrayEquals(new Class<?>[] {Void.class}, optional.getClassArray("classArray"));
AnnotationAttributes[] optionalArray = specialAttrs.getAnnotationArray("optionalArray");
assertThat(optionalArray.length, is(1));
assertThat(optionalArray[0].getString("value"), is("optional"));
assertThat(optionalArray.length).isEqualTo(1);
assertThat(optionalArray[0].getString("value")).isEqualTo("optional");
assertTrue(optionalArray[0].getEnum("anEnum").equals(SomeEnum.DEFAULT));
assertArrayEquals(new Class<?>[] {Void.class}, (Class<?>[]) optionalArray[0].get("classArray"));
assertArrayEquals(new Class<?>[] {Void.class}, optionalArray[0].getClassArray("classArray"));
assertEquals("direct", metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value"));
allMeta = metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("value");
assertThat(new HashSet<>(allMeta), is(equalTo(new HashSet<Object>(Arrays.asList("direct", "meta")))));
assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet<Object>(Arrays.asList("direct", "meta")));
allMeta = metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("additional");
assertThat(new HashSet<>(allMeta), is(equalTo(new HashSet<Object>(Arrays.asList("direct", "")))));
assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet<Object>(Arrays.asList("direct", "")));
assertEquals("", metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("additional"));
assertEquals(0, ((String[]) metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("additionalArray")).length);
}
{ // perform tests with classValuesAsString = true
AnnotationAttributes specialAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(
SpecialAttr.class.getName(), true);
assertThat(specialAttrs.size(), is(6));
assertThat(specialAttrs.get("clazz"), is((Object) String.class.getName()));
assertThat(specialAttrs.getString("clazz"), is(String.class.getName()));
assertThat(specialAttrs).hasSize(6);
assertThat(specialAttrs.get("clazz")).isEqualTo(String.class.getName());
assertThat(specialAttrs.getString("clazz")).isEqualTo(String.class.getName());
AnnotationAttributes nestedAnno = specialAttrs.getAnnotation("nestedAnno");
assertArrayEquals(new String[] { String.class.getName() }, nestedAnno.getStringArray("classArray"));
@@ -381,15 +373,15 @@ public class AnnotationMetadataTests {
assertEquals("direct", metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value"));
allMeta = metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("value");
assertThat(new HashSet<>(allMeta), is(equalTo(new HashSet<Object>(Arrays.asList("direct", "meta")))));
assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet<Object>(Arrays.asList("direct", "meta")));
}
}
private void doTestMethodAnnotationInfo(AnnotationMetadata classMetadata) {
Set<MethodMetadata> methods = classMetadata.getAnnotatedMethods(TestAutowired.class.getName());
assertThat(methods.size(), is(1));
assertThat(methods).hasSize(1);
for (MethodMetadata methodMetadata : methods) {
assertThat(methodMetadata.isAnnotated(TestAutowired.class.getName()), is(true));
assertThat(methodMetadata.isAnnotated(TestAutowired.class.getName())).isTrue();
}
}

View File

@@ -28,8 +28,8 @@ import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for checking the behaviour of {@link CachingMetadataReaderFactory} under
@@ -51,7 +51,7 @@ public class CachingMetadataReaderLeakTests {
// the biggest public class in the JDK (>60k)
URL url = getClass().getResource("/java/awt/Component.class");
assertThat(url, notNullValue());
assertThat(url).isNotNull();
// look at a LOT of items
for (int i = 0; i < ITEMS_TO_LOAD; i++) {
@@ -69,7 +69,7 @@ public class CachingMetadataReaderLeakTests {
};
MetadataReader reader = mrf.getMetadataReader(resource);
assertThat(reader, notNullValue());
assertThat(reader).isNotNull();
}
// useful for profiling to take snapshots

View File

@@ -24,10 +24,7 @@ import org.junit.Before;
import org.junit.Test;
import static java.util.stream.Collectors.joining;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.springframework.tests.Assume.TEST_GROUPS_SYSTEM_PROPERTY;
import static org.springframework.tests.TestGroup.CI;
@@ -108,13 +105,13 @@ public class AssumeTests {
fail("assumption should have failed");
}
catch (IllegalStateException ex) {
assertThat(ex.getMessage(),
startsWith("Failed to parse '" + TEST_GROUPS_SYSTEM_PROPERTY + "' system property: "));
assertThat(ex.getMessage()).
startsWith("Failed to parse '" + TEST_GROUPS_SYSTEM_PROPERTY + "' system property: ");
assertThat(ex.getCause(), instanceOf(IllegalArgumentException.class));
assertThat(ex.getCause().getMessage(),
equalTo("Unable to find test group 'bogus' when parsing testGroups value: '" + testGroups
+ "'. Available groups include: [LONG_RUNNING,PERFORMANCE,CI]"));
assertThat(ex.getCause()).isInstanceOf(IllegalArgumentException.class);
assertThat(ex.getCause().getMessage()).
isEqualTo("Unable to find test group 'bogus' when parsing testGroups value: '" + testGroups
+ "'. Available groups include: [LONG_RUNNING,PERFORMANCE,CI]");
}
}

View File

@@ -23,9 +23,10 @@ import org.mockito.internal.stubbing.InvocationContainerImpl;
import org.mockito.internal.util.MockUtil;
import org.mockito.invocation.Invocation;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.assertj.core.api.Assertions.assertThat;
/**
* General test utilities for use with {@link Mockito}.
@@ -52,7 +53,7 @@ public abstract class MockitoUtils {
private static void verifySameInvocations(List<Invocation> expectedInvocations, List<Invocation> actualInvocations,
InvocationArgumentsAdapter... argumentAdapters) {
assertThat(expectedInvocations.size(), is(equalTo(actualInvocations.size())));
assertThat(expectedInvocations.size()).isEqualTo(actualInvocations.size());
for (int i = 0; i < expectedInvocations.size(); i++) {
verifySameInvocation(expectedInvocations.get(i), actualInvocations.get(i), argumentAdapters);
}
@@ -61,10 +62,10 @@ public abstract class MockitoUtils {
private static void verifySameInvocation(Invocation expectedInvocation, Invocation actualInvocation,
InvocationArgumentsAdapter... argumentAdapters) {
assertThat(expectedInvocation.getMethod(), is(equalTo(actualInvocation.getMethod())));
assertThat(expectedInvocation.getMethod()).isEqualTo(actualInvocation.getMethod());
Object[] expectedArguments = getInvocationArguments(expectedInvocation, argumentAdapters);
Object[] actualArguments = getInvocationArguments(actualInvocation, argumentAdapters);
assertThat(expectedArguments, is(equalTo(actualArguments)));
assertThat(expectedArguments).isEqualTo(actualArguments);
}
private static Object[] getInvocationArguments(Invocation invocation, InvocationArgumentsAdapter... argumentAdapters) {

View File

@@ -22,9 +22,9 @@ import java.util.Set;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
/**
* Tests for {@link TestGroup}.
@@ -36,29 +36,29 @@ public class TestGroupTests {
@Test
public void parseNull() {
assertThat(TestGroup.parse(null), equalTo(Collections.emptySet()));
assertThat(TestGroup.parse(null)).isEqualTo(Collections.emptySet());
}
@Test
public void parseEmptyString() {
assertThat(TestGroup.parse(""), equalTo(Collections.emptySet()));
assertThat(TestGroup.parse("")).isEqualTo(Collections.emptySet());
}
@Test
public void parseBlankString() {
assertThat(TestGroup.parse(" "), equalTo(Collections.emptySet()));
assertThat(TestGroup.parse(" ")).isEqualTo(Collections.emptySet());
}
@Test
public void parseWithSpaces() {
assertThat(TestGroup.parse(" PERFORMANCE, PERFORMANCE "),
equalTo(EnumSet.of(TestGroup.PERFORMANCE)));
assertThat(TestGroup.parse(" PERFORMANCE, PERFORMANCE ")).containsOnly(
TestGroup.PERFORMANCE);
}
@Test
public void parseInMixedCase() {
assertThat(TestGroup.parse("performance, PERFormaNCE"),
equalTo(EnumSet.of(TestGroup.PERFORMANCE)));
assertThat(TestGroup.parse("performance, PERFormaNCE")).containsOnly(
TestGroup.PERFORMANCE);
}
@Test
@@ -72,14 +72,14 @@ public class TestGroupTests {
@Test
public void parseAll() {
assertThat(TestGroup.parse("all"), equalTo(EnumSet.allOf(TestGroup.class)));
assertThat(TestGroup.parse("all")).isEqualTo(EnumSet.allOf(TestGroup.class));
}
@Test
public void parseAllExceptPerformance() {
Set<TestGroup> expected = EnumSet.allOf(TestGroup.class);
expected.remove(TestGroup.PERFORMANCE);
assertThat(TestGroup.parse("all-performance"), equalTo(expected));
assertThat(TestGroup.parse("all-performance")).isEqualTo(expected);
}
@Test

View File

@@ -0,0 +1,54 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.tests;
import java.io.StringWriter;
import org.assertj.core.api.AssertProvider;
import org.xmlunit.assertj.XmlAssert;
/**
* {@link AssertProvider} to allow XML content assertions. Ultimately delegates
* to {@link XmlAssert}.
*
* @author Phillip Webb
*/
public class XmlContent implements AssertProvider<XmlContentAssert> {
private Object source;
private XmlContent(Object source) {
this.source = source;
}
@Override
public XmlContentAssert assertThat() {
return new XmlContentAssert(this.source);
}
public static XmlContent from(Object source) {
return of(source);
}
public static XmlContent of(Object source) {
if (source instanceof StringWriter) {
return of(source.toString());
}
return new XmlContent(source);
}
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.tests;
import org.assertj.core.api.AbstractAssert;
import org.w3c.dom.Node;
import org.xmlunit.assertj.XmlAssert;
import org.xmlunit.diff.DifferenceEvaluator;
import org.xmlunit.diff.NodeMatcher;
import org.xmlunit.util.Predicate;
/**
* Assertions exposed by {@link XmlContent}.
*
* @author Phillip Webb
*/
public class XmlContentAssert extends AbstractAssert<XmlContentAssert, Object> {
XmlContentAssert(Object actual) {
super(actual, XmlContentAssert.class);
}
public XmlContentAssert isSimilarTo(Object control) {
XmlAssert.assertThat(actual).and(control).areSimilar();
return this;
}
public XmlContentAssert isSimilarTo(Object control, Predicate<Node> nodeFilter) {
XmlAssert.assertThat(actual).and(control).withNodeFilter(nodeFilter).areSimilar();
return this;
}
public XmlContentAssert isSimilarTo(String control,
DifferenceEvaluator differenceEvaluator) {
XmlAssert.assertThat(actual).and(control).withDifferenceEvaluator(
differenceEvaluator).areSimilar();
return this;
}
public XmlContentAssert isSimilarToIgnoringWhitespace(Object control) {
XmlAssert.assertThat(actual).and(control).ignoreWhitespace().areSimilar();
return this;
}
public XmlContentAssert isSimilarToIgnoringWhitespace(String control, NodeMatcher nodeMatcher) {
XmlAssert.assertThat(actual).and(control).ignoreWhitespace().withNodeMatcher(nodeMatcher).areSimilar();
return this;
}
}

View File

@@ -39,12 +39,8 @@ import org.springframework.util.ConcurrentReferenceHashMap.Restructure;
import org.springframework.util.comparator.ComparableComparator;
import org.springframework.util.comparator.NullSafeComparator;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertFalse;
/**
@@ -63,43 +59,43 @@ public class ConcurrentReferenceHashMapTests {
@Test
public void shouldCreateWithDefaults() {
ConcurrentReferenceHashMap<Integer, String> map = new ConcurrentReferenceHashMap<>();
assertThat(map.getSegmentsSize(), is(16));
assertThat(map.getSegment(0).getSize(), is(1));
assertThat(map.getLoadFactor(), is(0.75f));
assertThat(map.getSegmentsSize()).isEqualTo(16);
assertThat(map.getSegment(0).getSize()).isEqualTo(1);
assertThat(map.getLoadFactor()).isEqualTo(0.75f);
}
@Test
public void shouldCreateWithInitialCapacity() {
ConcurrentReferenceHashMap<Integer, String> map = new ConcurrentReferenceHashMap<>(32);
assertThat(map.getSegmentsSize(), is(16));
assertThat(map.getSegment(0).getSize(), is(2));
assertThat(map.getLoadFactor(), is(0.75f));
assertThat(map.getSegmentsSize()).isEqualTo(16);
assertThat(map.getSegment(0).getSize()).isEqualTo(2);
assertThat(map.getLoadFactor()).isEqualTo(0.75f);
}
@Test
public void shouldCreateWithInitialCapacityAndLoadFactor() {
ConcurrentReferenceHashMap<Integer, String> map = new ConcurrentReferenceHashMap<>(32, 0.5f);
assertThat(map.getSegmentsSize(), is(16));
assertThat(map.getSegment(0).getSize(), is(2));
assertThat(map.getLoadFactor(), is(0.5f));
assertThat(map.getSegmentsSize()).isEqualTo(16);
assertThat(map.getSegment(0).getSize()).isEqualTo(2);
assertThat(map.getLoadFactor()).isEqualTo(0.5f);
}
@Test
public void shouldCreateWithInitialCapacityAndConcurrentLevel() {
ConcurrentReferenceHashMap<Integer, String> map = new ConcurrentReferenceHashMap<>(16, 2);
assertThat(map.getSegmentsSize(), is(2));
assertThat(map.getSegment(0).getSize(), is(8));
assertThat(map.getLoadFactor(), is(0.75f));
assertThat(map.getSegmentsSize()).isEqualTo(2);
assertThat(map.getSegment(0).getSize()).isEqualTo(8);
assertThat(map.getLoadFactor()).isEqualTo(0.75f);
}
@Test
public void shouldCreateFullyCustom() {
ConcurrentReferenceHashMap<Integer, String> map = new ConcurrentReferenceHashMap<>(5, 0.5f, 3);
// concurrencyLevel of 3 ends up as 4 (nearest power of 2)
assertThat(map.getSegmentsSize(), is(4));
assertThat(map.getSegmentsSize()).isEqualTo(4);
// initialCapacity is 5/4 (rounded up, to nearest power of 2)
assertThat(map.getSegment(0).getSize(), is(2));
assertThat(map.getLoadFactor(), is(0.5f));
assertThat(map.getSegment(0).getSize()).isEqualTo(2);
assertThat(map.getLoadFactor()).isEqualTo(0.5f);
}
@Test
@@ -129,55 +125,55 @@ public class ConcurrentReferenceHashMapTests {
@Test
public void shouldPutAndGet() {
// NOTE we are using mock references so we don't need to worry about GC
assertThat(this.map.size(), is(0));
assertThat(this.map).hasSize(0);
this.map.put(123, "123");
assertThat(this.map.get(123), is("123"));
assertThat(this.map.size(), is(1));
assertThat(this.map.get(123)).isEqualTo("123");
assertThat(this.map).hasSize(1);
this.map.put(123, "123b");
assertThat(this.map.size(), is(1));
assertThat(this.map).hasSize(1);
this.map.put(123, null);
assertThat(this.map.size(), is(1));
assertThat(this.map).hasSize(1);
}
@Test
public void shouldReplaceOnDoublePut() {
this.map.put(123, "321");
this.map.put(123, "123");
assertThat(this.map.get(123), is("123"));
assertThat(this.map.get(123)).isEqualTo("123");
}
@Test
public void shouldPutNullKey() {
assertThat(this.map.get(null), is(nullValue()));
assertThat(this.map.getOrDefault(null, "456"), is("456"));
assertThat(this.map.get(null)).isNull();
assertThat(this.map.getOrDefault(null, "456")).isEqualTo("456");
this.map.put(null, "123");
assertThat(this.map.get(null), is("123"));
assertThat(this.map.getOrDefault(null, "456"), is("123"));
assertThat(this.map.get(null)).isEqualTo("123");
assertThat(this.map.getOrDefault(null, "456")).isEqualTo("123");
}
@Test
public void shouldPutNullValue() {
assertThat(this.map.get(123), is(nullValue()));
assertThat(this.map.getOrDefault(123, "456"), is("456"));
assertThat(this.map.get(123)).isNull();
assertThat(this.map.getOrDefault(123, "456")).isEqualTo("456");
this.map.put(123, "321");
assertThat(this.map.get(123), is("321"));
assertThat(this.map.getOrDefault(123, "456"), is("321"));
assertThat(this.map.get(123)).isEqualTo("321");
assertThat(this.map.getOrDefault(123, "456")).isEqualTo("321");
this.map.put(123, null);
assertThat(this.map.get(123), is(nullValue()));
assertThat(this.map.getOrDefault(123, "456"), is(nullValue()));
assertThat(this.map.get(123)).isNull();
assertThat(this.map.getOrDefault(123, "456")).isNull();
}
@Test
public void shouldGetWithNoItems() {
assertThat(this.map.get(123), is(nullValue()));
assertThat(this.map.get(123)).isNull();
}
@Test
public void shouldApplySupplementalHash() {
Integer key = 123;
this.map.put(key, "123");
assertThat(this.map.getSupplementalHash(), is(not(key.hashCode())));
assertThat(this.map.getSupplementalHash() >> 30 & 0xFF, is(not(0)));
assertThat(this.map.getSupplementalHash()).isNotEqualTo(key.hashCode());
assertThat(this.map.getSupplementalHash() >> 30 & 0xFF).isNotEqualTo(0);
}
@Test
@@ -187,41 +183,41 @@ public class ConcurrentReferenceHashMapTests {
this.map.put(1, "1");
this.map.put(2, "2");
this.map.put(3, "3");
assertThat(this.map.getSegment(0).getSize(), is(1));
assertThat(this.map.get(1), is("1"));
assertThat(this.map.get(2), is("2"));
assertThat(this.map.get(3), is("3"));
assertThat(this.map.get(4), is(nullValue()));
assertThat(this.map.getSegment(0).getSize()).isEqualTo(1);
assertThat(this.map.get(1)).isEqualTo("1");
assertThat(this.map.get(2)).isEqualTo("2");
assertThat(this.map.get(3)).isEqualTo("3");
assertThat(this.map.get(4)).isNull();
}
@Test
public void shouldResize() {
this.map = new TestWeakConcurrentCache<>(1, 0.75f, 1);
this.map.put(1, "1");
assertThat(this.map.getSegment(0).getSize(), is(1));
assertThat(this.map.get(1), is("1"));
assertThat(this.map.getSegment(0).getSize()).isEqualTo(1);
assertThat(this.map.get(1)).isEqualTo("1");
this.map.put(2, "2");
assertThat(this.map.getSegment(0).getSize(), is(2));
assertThat(this.map.get(1), is("1"));
assertThat(this.map.get(2), is("2"));
assertThat(this.map.getSegment(0).getSize()).isEqualTo(2);
assertThat(this.map.get(1)).isEqualTo("1");
assertThat(this.map.get(2)).isEqualTo("2");
this.map.put(3, "3");
assertThat(this.map.getSegment(0).getSize(), is(4));
assertThat(this.map.get(1), is("1"));
assertThat(this.map.get(2), is("2"));
assertThat(this.map.get(3), is("3"));
assertThat(this.map.getSegment(0).getSize()).isEqualTo(4);
assertThat(this.map.get(1)).isEqualTo("1");
assertThat(this.map.get(2)).isEqualTo("2");
assertThat(this.map.get(3)).isEqualTo("3");
this.map.put(4, "4");
assertThat(this.map.getSegment(0).getSize(), is(8));
assertThat(this.map.get(4), is("4"));
assertThat(this.map.getSegment(0).getSize()).isEqualTo(8);
assertThat(this.map.get(4)).isEqualTo("4");
// Putting again should not increase the count
for (int i = 1; i <= 5; i++) {
this.map.put(i, String.valueOf(i));
}
assertThat(this.map.getSegment(0).getSize(), is(8));
assertThat(this.map.get(5), is("5"));
assertThat(this.map.getSegment(0).getSize()).isEqualTo(8);
assertThat(this.map.get(5)).isEqualTo("5");
}
@Test
@@ -232,11 +228,11 @@ public class ConcurrentReferenceHashMapTests {
}
this.map.getMockReference(1, Restructure.NEVER).queueForPurge();
this.map.getMockReference(3, Restructure.NEVER).queueForPurge();
assertThat(this.map.getReference(1, Restructure.WHEN_NECESSARY), is(nullValue()));
assertThat(this.map.get(2), is("2"));
assertThat(this.map.getReference(3, Restructure.WHEN_NECESSARY), is(nullValue()));
assertThat(this.map.get(4), is("4"));
assertThat(this.map.get(5), is("5"));
assertThat(this.map.getReference(1, Restructure.WHEN_NECESSARY)).isNull();
assertThat(this.map.get(2)).isEqualTo("2");
assertThat(this.map.getReference(3, Restructure.WHEN_NECESSARY)).isNull();
assertThat(this.map.get(4)).isEqualTo("4");
assertThat(this.map.get(5)).isEqualTo("5");
}
@Test
@@ -248,122 +244,122 @@ public class ConcurrentReferenceHashMapTests {
this.map.getMockReference(1, Restructure.NEVER).queueForPurge();
this.map.getMockReference(3, Restructure.NEVER).queueForPurge();
this.map.put(1, "1");
assertThat(this.map.get(1), is("1"));
assertThat(this.map.get(2), is("2"));
assertThat(this.map.getReference(3, Restructure.WHEN_NECESSARY), is(nullValue()));
assertThat(this.map.get(4), is("4"));
assertThat(this.map.get(5), is("5"));
assertThat(this.map.get(1)).isEqualTo("1");
assertThat(this.map.get(2)).isEqualTo("2");
assertThat(this.map.getReference(3, Restructure.WHEN_NECESSARY)).isNull();
assertThat(this.map.get(4)).isEqualTo("4");
assertThat(this.map.get(5)).isEqualTo("5");
}
@Test
public void shouldPutIfAbsent() {
assertThat(this.map.putIfAbsent(123, "123"), is(nullValue()));
assertThat(this.map.putIfAbsent(123, "123b"), is("123"));
assertThat(this.map.get(123), is("123"));
assertThat(this.map.putIfAbsent(123, "123")).isNull();
assertThat(this.map.putIfAbsent(123, "123b")).isEqualTo("123");
assertThat(this.map.get(123)).isEqualTo("123");
}
@Test
public void shouldPutIfAbsentWithNullValue() {
assertThat(this.map.putIfAbsent(123, null), is(nullValue()));
assertThat(this.map.putIfAbsent(123, "123"), is(nullValue()));
assertThat(this.map.get(123), is(nullValue()));
assertThat(this.map.putIfAbsent(123, null)).isNull();
assertThat(this.map.putIfAbsent(123, "123")).isNull();
assertThat(this.map.get(123)).isNull();
}
@Test
public void shouldPutIfAbsentWithNullKey() {
assertThat(this.map.putIfAbsent(null, "123"), is(nullValue()));
assertThat(this.map.putIfAbsent(null, "123b"), is("123"));
assertThat(this.map.get(null), is("123"));
assertThat(this.map.putIfAbsent(null, "123")).isNull();
assertThat(this.map.putIfAbsent(null, "123b")).isEqualTo("123");
assertThat(this.map.get(null)).isEqualTo("123");
}
@Test
public void shouldRemoveKeyAndValue() {
this.map.put(123, "123");
assertThat(this.map.remove(123, "456"), is(false));
assertThat(this.map.get(123), is("123"));
assertThat(this.map.remove(123, "123"), is(true));
assertThat(this.map.remove(123, "456")).isFalse();
assertThat(this.map.get(123)).isEqualTo("123");
assertThat(this.map.remove(123, "123")).isTrue();
assertFalse(this.map.containsKey(123));
assertThat(this.map.isEmpty(), is(true));
assertThat(this.map.isEmpty()).isTrue();
}
@Test
public void shouldRemoveKeyAndValueWithExistingNull() {
this.map.put(123, null);
assertThat(this.map.remove(123, "456"), is(false));
assertThat(this.map.get(123), is(nullValue()));
assertThat(this.map.remove(123, null), is(true));
assertThat(this.map.remove(123, "456")).isFalse();
assertThat(this.map.get(123)).isNull();
assertThat(this.map.remove(123, null)).isTrue();
assertFalse(this.map.containsKey(123));
assertThat(this.map.isEmpty(), is(true));
assertThat(this.map.isEmpty()).isTrue();
}
@Test
public void shouldReplaceOldValueWithNewValue() {
this.map.put(123, "123");
assertThat(this.map.replace(123, "456", "789"), is(false));
assertThat(this.map.get(123), is("123"));
assertThat(this.map.replace(123, "123", "789"), is(true));
assertThat(this.map.get(123), is("789"));
assertThat(this.map.replace(123, "456", "789")).isFalse();
assertThat(this.map.get(123)).isEqualTo("123");
assertThat(this.map.replace(123, "123", "789")).isTrue();
assertThat(this.map.get(123)).isEqualTo("789");
}
@Test
public void shouldReplaceOldNullValueWithNewValue() {
this.map.put(123, null);
assertThat(this.map.replace(123, "456", "789"), is(false));
assertThat(this.map.get(123), is(nullValue()));
assertThat(this.map.replace(123, null, "789"), is(true));
assertThat(this.map.get(123), is("789"));
assertThat(this.map.replace(123, "456", "789")).isFalse();
assertThat(this.map.get(123)).isNull();
assertThat(this.map.replace(123, null, "789")).isTrue();
assertThat(this.map.get(123)).isEqualTo("789");
}
@Test
public void shouldReplaceValue() {
this.map.put(123, "123");
assertThat(this.map.replace(123, "456"), is("123"));
assertThat(this.map.get(123), is("456"));
assertThat(this.map.replace(123, "456")).isEqualTo("123");
assertThat(this.map.get(123)).isEqualTo("456");
}
@Test
public void shouldReplaceNullValue() {
this.map.put(123, null);
assertThat(this.map.replace(123, "456"), is(nullValue()));
assertThat(this.map.get(123), is("456"));
assertThat(this.map.replace(123, "456")).isNull();
assertThat(this.map.get(123)).isEqualTo("456");
}
@Test
public void shouldGetSize() {
assertThat(this.map.size(), is(0));
assertThat(this.map).hasSize(0);
this.map.put(123, "123");
this.map.put(123, null);
this.map.put(456, "456");
assertThat(this.map.size(), is(2));
assertThat(this.map).hasSize(2);
}
@Test
public void shouldSupportIsEmpty() {
assertThat(this.map.isEmpty(), is(true));
assertThat(this.map.isEmpty()).isTrue();
this.map.put(123, "123");
this.map.put(123, null);
this.map.put(456, "456");
assertThat(this.map.isEmpty(), is(false));
assertThat(this.map.isEmpty()).isFalse();
}
@Test
public void shouldContainKey() {
assertThat(this.map.containsKey(123), is(false));
assertThat(this.map.containsKey(456), is(false));
assertThat(this.map.containsKey(123)).isFalse();
assertThat(this.map.containsKey(456)).isFalse();
this.map.put(123, "123");
this.map.put(456, null);
assertThat(this.map.containsKey(123), is(true));
assertThat(this.map.containsKey(456), is(true));
assertThat(this.map.containsKey(123)).isTrue();
assertThat(this.map.containsKey(456)).isTrue();
}
@Test
public void shouldContainValue() {
assertThat(this.map.containsValue("123"), is(false));
assertThat(this.map.containsValue(null), is(false));
assertThat(this.map.containsValue("123")).isFalse();
assertThat(this.map.containsValue(null)).isFalse();
this.map.put(123, "123");
this.map.put(456, null);
assertThat(this.map.containsValue("123"), is(true));
assertThat(this.map.containsValue(null), is(true));
assertThat(this.map.containsValue("123")).isTrue();
assertThat(this.map.containsValue(null)).isTrue();
}
@Test
@@ -371,17 +367,17 @@ public class ConcurrentReferenceHashMapTests {
this.map.put(123, null);
this.map.put(456, "456");
this.map.put(null, "789");
assertThat(this.map.remove(123), is(nullValue()));
assertThat(this.map.remove(456), is("456"));
assertThat(this.map.remove(null), is("789"));
assertThat(this.map.isEmpty(), is(true));
assertThat(this.map.remove(123)).isNull();
assertThat(this.map.remove(456)).isEqualTo("456");
assertThat(this.map.remove(null)).isEqualTo("789");
assertThat(this.map.isEmpty()).isTrue();
}
@Test
public void shouldRemoveWhenKeyIsNotInMap() {
assertThat(this.map.remove(123), is(nullValue()));
assertThat(this.map.remove(null), is(nullValue()));
assertThat(this.map.isEmpty(), is(true));
assertThat(this.map.remove(123)).isNull();
assertThat(this.map.remove(null)).isNull();
assertThat(this.map.isEmpty()).isTrue();
}
@Test
@@ -391,10 +387,10 @@ public class ConcurrentReferenceHashMapTests {
m.put(456, null);
m.put(null, "789");
this.map.putAll(m);
assertThat(this.map.size(), is(3));
assertThat(this.map.get(123), is("123"));
assertThat(this.map.get(456), is(nullValue()));
assertThat(this.map.get(null), is("789"));
assertThat(this.map).hasSize(3);
assertThat(this.map.get(123)).isEqualTo("123");
assertThat(this.map.get(456)).isNull();
assertThat(this.map.get(null)).isEqualTo("789");
}
@Test
@@ -403,10 +399,10 @@ public class ConcurrentReferenceHashMapTests {
this.map.put(456, null);
this.map.put(null, "789");
this.map.clear();
assertThat(this.map.size(), is(0));
assertThat(this.map.containsKey(123), is(false));
assertThat(this.map.containsKey(456), is(false));
assertThat(this.map.containsKey(null), is(false));
assertThat(this.map).hasSize(0);
assertThat(this.map.containsKey(123)).isFalse();
assertThat(this.map.containsKey(456)).isFalse();
assertThat(this.map.containsKey(null)).isFalse();
}
@Test
@@ -418,7 +414,7 @@ public class ConcurrentReferenceHashMapTests {
expected.add(123);
expected.add(456);
expected.add(null);
assertThat(this.map.keySet(), is(expected));
assertThat(this.map.keySet()).isEqualTo(expected);
}
@Test
@@ -433,7 +429,7 @@ public class ConcurrentReferenceHashMapTests {
expected.add("789");
actual.sort(NULL_SAFE_STRING_SORT);
expected.sort(NULL_SAFE_STRING_SORT);
assertThat(actual, is(expected));
assertThat(actual).isEqualTo(expected);
}
@Test
@@ -445,7 +441,7 @@ public class ConcurrentReferenceHashMapTests {
expected.put(123, "123");
expected.put(456, null);
expected.put(null, "789");
assertThat(this.map.entrySet(), is(expected.entrySet()));
assertThat(this.map.entrySet()).isEqualTo(expected.entrySet());
}
@Test
@@ -459,7 +455,7 @@ public class ConcurrentReferenceHashMapTests {
expected.put(1, "1");
expected.put(2, "2");
expected.put(3, "3");
assertThat(this.map.entrySet(), is(expected.entrySet()));
assertThat(this.map.entrySet()).isEqualTo(expected.entrySet());
}
@Test
@@ -472,9 +468,9 @@ public class ConcurrentReferenceHashMapTests {
iterator.next();
iterator.remove();
iterator.next();
assertThat(iterator.hasNext(), is(false));
assertThat(this.map.size(), is(2));
assertThat(this.map.containsKey(2), is(false));
assertThat(iterator.hasNext()).isFalse();
assertThat(this.map).hasSize(2);
assertThat(this.map.containsKey(2)).isFalse();
}
@Test
@@ -486,9 +482,9 @@ public class ConcurrentReferenceHashMapTests {
iterator.next();
iterator.next().setValue("2b");
iterator.next();
assertThat(iterator.hasNext(), is(false));
assertThat(this.map.size(), is(3));
assertThat(this.map.get(2), is("2b"));
assertThat(iterator.hasNext()).isFalse();
assertThat(this.map).hasSize(3);
assertThat(this.map.get(2)).isEqualTo("2b");
}
@Test
@@ -503,7 +499,7 @@ public class ConcurrentReferenceHashMapTests {
System.out.println(cacheTime.prettyPrint());
// We should be at least 4 time faster
assertThat(cacheTime.getTotalTimeSeconds(), is(lessThan(mapTime.getTotalTimeSeconds() / 4.0)));
assertThat(cacheTime.getTotalTimeSeconds()).isLessThan(mapTime.getTotalTimeSeconds() / 4.0);
}
@Test

View File

@@ -26,9 +26,8 @@ import java.util.Set;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -789,23 +788,23 @@ public class ObjectUtilsTests {
@Test
public void containsConstant() {
assertThat(ObjectUtils.containsConstant(Tropes.values(), "FOO"), is(true));
assertThat(ObjectUtils.containsConstant(Tropes.values(), "foo"), is(true));
assertThat(ObjectUtils.containsConstant(Tropes.values(), "BaR"), is(true));
assertThat(ObjectUtils.containsConstant(Tropes.values(), "bar"), is(true));
assertThat(ObjectUtils.containsConstant(Tropes.values(), "BAZ"), is(true));
assertThat(ObjectUtils.containsConstant(Tropes.values(), "baz"), is(true));
assertThat(ObjectUtils.containsConstant(Tropes.values(), "FOO")).isTrue();
assertThat(ObjectUtils.containsConstant(Tropes.values(), "foo")).isTrue();
assertThat(ObjectUtils.containsConstant(Tropes.values(), "BaR")).isTrue();
assertThat(ObjectUtils.containsConstant(Tropes.values(), "bar")).isTrue();
assertThat(ObjectUtils.containsConstant(Tropes.values(), "BAZ")).isTrue();
assertThat(ObjectUtils.containsConstant(Tropes.values(), "baz")).isTrue();
assertThat(ObjectUtils.containsConstant(Tropes.values(), "BOGUS"), is(false));
assertThat(ObjectUtils.containsConstant(Tropes.values(), "BOGUS")).isFalse();
assertThat(ObjectUtils.containsConstant(Tropes.values(), "FOO", true), is(true));
assertThat(ObjectUtils.containsConstant(Tropes.values(), "foo", true), is(false));
assertThat(ObjectUtils.containsConstant(Tropes.values(), "FOO", true)).isTrue();
assertThat(ObjectUtils.containsConstant(Tropes.values(), "foo", true)).isFalse();
}
@Test
public void caseInsensitiveValueOf() {
assertThat(ObjectUtils.caseInsensitiveValueOf(Tropes.values(), "foo"), is(Tropes.FOO));
assertThat(ObjectUtils.caseInsensitiveValueOf(Tropes.values(), "BAR"), is(Tropes.BAR));
assertThat(ObjectUtils.caseInsensitiveValueOf(Tropes.values(), "foo")).isEqualTo(Tropes.FOO);
assertThat(ObjectUtils.caseInsensitiveValueOf(Tropes.values(), "BAR")).isEqualTo(Tropes.BAR);
assertThatIllegalArgumentException().isThrownBy(() ->
ObjectUtils.caseInsensitiveValueOf(Tropes.values(), "bogus"))

View File

@@ -24,7 +24,6 @@ import java.rmi.RemoteException;
import java.util.LinkedList;
import java.util.List;
import org.hamcrest.Matchers;
import org.junit.Ignore;
import org.junit.Test;
@@ -32,11 +31,8 @@ import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup;
import org.springframework.tests.sample.objects.TestObject;
import static org.assertj.core.api.Assertions.assertThat;
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;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@@ -288,7 +284,7 @@ public class ReflectionUtilsTests {
toStringMethodCount++;
}
}
assertThat(toStringMethodCount, is(2));
assertThat(toStringMethodCount).isEqualTo(2);
}
@Test
@@ -305,7 +301,7 @@ public class ReflectionUtilsTests {
toStringMethodCount++;
}
}
assertThat(toStringMethodCount, is(1));
assertThat(toStringMethodCount).isEqualTo(1);
}
@Test
@@ -329,7 +325,7 @@ public class ReflectionUtilsTests {
m1MethodCount++;
}
}
assertThat(m1MethodCount, is(1));
assertThat(m1MethodCount).isEqualTo(1);
assertTrue(ObjectUtils.containsElement(methods, Leaf.class.getMethod("m1")));
assertFalse(ObjectUtils.containsElement(methods, Parent.class.getMethod("m1")));
}
@@ -367,15 +363,15 @@ public class ReflectionUtilsTests {
Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(C.class);
sw.stop();
long totalMs = sw.getTotalTimeMillis();
assertThat(methods.length, Matchers.greaterThan(100));
assertThat(totalMs, Matchers.lessThan(10L));
assertThat(methods.length).isGreaterThan(100);
assertThat(totalMs).isLessThan(10L);
}
@Test
public void getDecalredMethodsReturnsCopy() {
Method[] m1 = ReflectionUtils.getDeclaredMethods(A.class);
Method[] m2 = ReflectionUtils.getDeclaredMethods(A.class);
assertThat(m1, not(sameInstance(m2)));
assertThat(m1). isNotSameAs(m2);
}
private static class ListSavingMethodCallback implements ReflectionUtils.MethodCallback {

View File

@@ -29,8 +29,7 @@ import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -60,7 +59,7 @@ public class StreamUtilsTests {
public void copyToByteArray() throws Exception {
InputStream inputStream = spy(new ByteArrayInputStream(bytes));
byte[] actual = StreamUtils.copyToByteArray(inputStream);
assertThat(actual, equalTo(bytes));
assertThat(actual).isEqualTo(bytes);
verify(inputStream, never()).close();
}
@@ -69,7 +68,7 @@ public class StreamUtilsTests {
Charset charset = Charset.defaultCharset();
InputStream inputStream = spy(new ByteArrayInputStream(string.getBytes(charset)));
String actual = StreamUtils.copyToString(inputStream, charset);
assertThat(actual, equalTo(string));
assertThat(actual).isEqualTo(string);
verify(inputStream, never()).close();
}
@@ -77,7 +76,7 @@ public class StreamUtilsTests {
public void copyBytes() throws Exception {
ByteArrayOutputStream out = spy(new ByteArrayOutputStream());
StreamUtils.copy(bytes, out);
assertThat(out.toByteArray(), equalTo(bytes));
assertThat(out.toByteArray()).isEqualTo(bytes);
verify(out, never()).close();
}
@@ -86,7 +85,7 @@ public class StreamUtilsTests {
Charset charset = Charset.defaultCharset();
ByteArrayOutputStream out = spy(new ByteArrayOutputStream());
StreamUtils.copy(string, charset, out);
assertThat(out.toByteArray(), equalTo(string.getBytes(charset)));
assertThat(out.toByteArray()).isEqualTo(string.getBytes(charset));
verify(out, never()).close();
}
@@ -94,7 +93,7 @@ public class StreamUtilsTests {
public void copyStream() throws Exception {
ByteArrayOutputStream out = spy(new ByteArrayOutputStream());
StreamUtils.copy(new ByteArrayInputStream(bytes), out);
assertThat(out.toByteArray(), equalTo(bytes));
assertThat(out.toByteArray()).isEqualTo(bytes);
verify(out, never()).close();
}
@@ -103,7 +102,7 @@ public class StreamUtilsTests {
ByteArrayOutputStream out = spy(new ByteArrayOutputStream());
StreamUtils.copyRange(new ByteArrayInputStream(bytes), out, 0, 100);
byte[] range = Arrays.copyOfRange(bytes, 0, 101);
assertThat(out.toByteArray(), equalTo(range));
assertThat(out.toByteArray()).isEqualTo(range);
verify(out, never()).close();
}

View File

@@ -20,8 +20,8 @@ import java.util.Comparator;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link BooleanComparator}.
@@ -35,29 +35,29 @@ public class BooleanComparatorTests {
@Test
public void shouldCompareWithTrueLow() {
Comparator<Boolean> c = new BooleanComparator(true);
assertThat(c.compare(true, false), is(-1));
assertThat(c.compare(Boolean.TRUE, Boolean.TRUE), is(0));
assertThat(c.compare(true, false)).isEqualTo(-1);
assertThat(c.compare(Boolean.TRUE, Boolean.TRUE)).isEqualTo(0);
}
@Test
public void shouldCompareWithTrueHigh() {
Comparator<Boolean> c = new BooleanComparator(false);
assertThat(c.compare(true, false), is(1));
assertThat(c.compare(Boolean.TRUE, Boolean.TRUE), is(0));
assertThat(c.compare(true, false)).isEqualTo(1);
assertThat(c.compare(Boolean.TRUE, Boolean.TRUE)).isEqualTo(0);
}
@Test
public void shouldCompareFromTrueLow() {
Comparator<Boolean> c = BooleanComparator.TRUE_LOW;
assertThat(c.compare(true, false), is(-1));
assertThat(c.compare(Boolean.TRUE, Boolean.TRUE), is(0));
assertThat(c.compare(true, false)).isEqualTo(-1);
assertThat(c.compare(Boolean.TRUE, Boolean.TRUE)).isEqualTo(0);
}
@Test
public void shouldCompareFromTrueHigh() {
Comparator<Boolean> c = BooleanComparator.TRUE_HIGH;
assertThat(c.compare(true, false), is(1));
assertThat(c.compare(Boolean.TRUE, Boolean.TRUE), is(0));
assertThat(c.compare(true, false)).isEqualTo(1);
assertThat(c.compare(Boolean.TRUE, Boolean.TRUE)).isEqualTo(0);
}
}

View File

@@ -20,8 +20,8 @@ import java.util.Comparator;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link InstanceComparator}.
@@ -41,32 +41,32 @@ public class InstanceComparatorTests {
@Test
public void shouldCompareClasses() throws Exception {
Comparator<Object> comparator = new InstanceComparator<>(C1.class, C2.class);
assertThat(comparator.compare(c1, c1), is(0));
assertThat(comparator.compare(c1, c2), is(-1));
assertThat(comparator.compare(c2, c1), is(1));
assertThat(comparator.compare(c2, c3), is(-1));
assertThat(comparator.compare(c2, c4), is(-1));
assertThat(comparator.compare(c3, c4), is(0));
assertThat(comparator.compare(c1, c1)).isEqualTo(0);
assertThat(comparator.compare(c1, c2)).isEqualTo(-1);
assertThat(comparator.compare(c2, c1)).isEqualTo(1);
assertThat(comparator.compare(c2, c3)).isEqualTo(-1);
assertThat(comparator.compare(c2, c4)).isEqualTo(-1);
assertThat(comparator.compare(c3, c4)).isEqualTo(0);
}
@Test
public void shouldCompareInterfaces() throws Exception {
Comparator<Object> comparator = new InstanceComparator<>(I1.class, I2.class);
assertThat(comparator.compare(c1, c1), is(0));
assertThat(comparator.compare(c1, c2), is(0));
assertThat(comparator.compare(c2, c1), is(0));
assertThat(comparator.compare(c1, c3), is(-1));
assertThat(comparator.compare(c3, c1), is(1));
assertThat(comparator.compare(c3, c4), is(0));
assertThat(comparator.compare(c1, c1)).isEqualTo(0);
assertThat(comparator.compare(c1, c2)).isEqualTo(0);
assertThat(comparator.compare(c2, c1)).isEqualTo(0);
assertThat(comparator.compare(c1, c3)).isEqualTo(-1);
assertThat(comparator.compare(c3, c1)).isEqualTo(1);
assertThat(comparator.compare(c3, c4)).isEqualTo(0);
}
@Test
public void shouldCompareMix() throws Exception {
Comparator<Object> comparator = new InstanceComparator<>(I1.class, C3.class);
assertThat(comparator.compare(c1, c1), is(0));
assertThat(comparator.compare(c3, c4), is(-1));
assertThat(comparator.compare(c3, null), is(-1));
assertThat(comparator.compare(c4, null), is(0));
assertThat(comparator.compare(c1, c1)).isEqualTo(0);
assertThat(comparator.compare(c3, c4)).isEqualTo(-1);
assertThat(comparator.compare(c3, null)).isEqualTo(-1);
assertThat(comparator.compare(c4, null)).isEqualTo(0);
}
private static interface I1 {

View File

@@ -20,9 +20,9 @@ import java.util.Comparator;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Tests for {@link InvertibleComparator}.
@@ -52,30 +52,30 @@ public class InvertibleComparatorTests {
@Test
public void shouldDefaultToAscending() throws Exception {
InvertibleComparator<Integer> invertibleComparator = new InvertibleComparator<>(comparator);
assertThat(invertibleComparator.isAscending(), is(true));
assertThat(invertibleComparator.compare(1, 2), is(-1));
assertThat(invertibleComparator.isAscending()).isTrue();
assertThat(invertibleComparator.compare(1, 2)).isEqualTo(-1);
}
@Test
public void shouldInvert() throws Exception {
InvertibleComparator<Integer> invertibleComparator = new InvertibleComparator<>(comparator);
assertThat(invertibleComparator.isAscending(), is(true));
assertThat(invertibleComparator.compare(1, 2), is(-1));
assertThat(invertibleComparator.isAscending()).isTrue();
assertThat(invertibleComparator.compare(1, 2)).isEqualTo(-1);
invertibleComparator.invertOrder();
assertThat(invertibleComparator.isAscending(), is(false));
assertThat(invertibleComparator.compare(1, 2), is(1));
assertThat(invertibleComparator.isAscending()).isFalse();
assertThat(invertibleComparator.compare(1, 2)).isEqualTo(1);
}
@Test
public void shouldCompareAscending() throws Exception {
InvertibleComparator<Integer> invertibleComparator = new InvertibleComparator<>(comparator, true);
assertThat(invertibleComparator.compare(1, 2), is(-1));
assertThat(invertibleComparator.compare(1, 2)).isEqualTo(-1);
}
@Test
public void shouldCompareDescending() throws Exception {
InvertibleComparator<Integer> invertibleComparator = new InvertibleComparator<>(comparator, false);
assertThat(invertibleComparator.compare(1, 2), is(1));
assertThat(invertibleComparator.compare(1, 2)).isEqualTo(1);
}
}

View File

@@ -24,9 +24,8 @@ import java.util.concurrent.TimeoutException;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
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;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@@ -55,7 +54,7 @@ public class SettableListenableFutureTests {
public void returnsSetValue() throws ExecutionException, InterruptedException {
String string = "hello";
assertTrue(settableListenableFuture.set(string));
assertThat(settableListenableFuture.get(), equalTo(string));
assertThat(settableListenableFuture.get()).isEqualTo(string);
assertFalse(settableListenableFuture.isCancelled());
assertTrue(settableListenableFuture.isDone());
}
@@ -65,7 +64,7 @@ public class SettableListenableFutureTests {
String string = "hello";
assertTrue(settableListenableFuture.set(string));
Future<String> completable = settableListenableFuture.completable();
assertThat(completable.get(), equalTo(string));
assertThat(completable.get()).isEqualTo(string);
assertFalse(completable.isCancelled());
assertTrue(completable.isDone());
}
@@ -148,7 +147,7 @@ public class SettableListenableFutureTests {
});
settableListenableFuture.set(string);
assertThat(callbackHolder[0], equalTo(string));
assertThat(callbackHolder[0]).isEqualTo(string);
assertFalse(settableListenableFuture.isCancelled());
assertTrue(settableListenableFuture.isDone());
}
@@ -171,7 +170,7 @@ public class SettableListenableFutureTests {
settableListenableFuture.set(string);
assertFalse(settableListenableFuture.set("good bye"));
assertThat(callbackHolder[0], equalTo(string));
assertThat(callbackHolder[0]).isEqualTo(string);
assertFalse(settableListenableFuture.isCancelled());
assertTrue(settableListenableFuture.isDone());
}
@@ -193,7 +192,7 @@ public class SettableListenableFutureTests {
});
settableListenableFuture.setException(exception);
assertThat(callbackHolder[0], equalTo(exception));
assertThat(callbackHolder[0]).isEqualTo(exception);
assertFalse(settableListenableFuture.isCancelled());
assertTrue(settableListenableFuture.isDone());
}
@@ -216,7 +215,7 @@ public class SettableListenableFutureTests {
settableListenableFuture.setException(exception);
assertFalse(settableListenableFuture.setException(new IllegalArgumentException()));
assertThat(callbackHolder[0], equalTo(exception));
assertThat(callbackHolder[0]).isEqualTo(exception);
assertFalse(settableListenableFuture.isCancelled());
assertTrue(settableListenableFuture.isDone());
}
@@ -247,7 +246,7 @@ public class SettableListenableFutureTests {
}).start();
String value = settableListenableFuture.get();
assertThat(value, equalTo(string));
assertThat(value).isEqualTo(string);
assertFalse(settableListenableFuture.isCancelled());
assertTrue(settableListenableFuture.isDone());
}
@@ -276,7 +275,7 @@ public class SettableListenableFutureTests {
}).start();
String value = settableListenableFuture.get(500L, TimeUnit.MILLISECONDS);
assertThat(value, equalTo(string));
assertThat(value).isEqualTo(string);
assertFalse(settableListenableFuture.isCancelled());
assertTrue(settableListenableFuture.isDone());
}

View File

@@ -33,8 +33,9 @@ import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xmlunit.util.Predicate;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
import org.springframework.tests.XmlContent;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Arjen Poutsma
@@ -80,7 +81,7 @@ public abstract class AbstractStaxHandlerTestCase {
xmlReader.parse(new InputSource(new StringReader(COMPLEX_XML)));
assertThat(stringWriter.toString(), isSimilarTo(COMPLEX_XML).withNodeFilter(nodeFilter));
assertThat(XmlContent.from(stringWriter)).isSimilarTo(COMPLEX_XML, nodeFilter);
}
@Test
@@ -95,7 +96,7 @@ public abstract class AbstractStaxHandlerTestCase {
xmlReader.parse(new InputSource(new StringReader(COMPLEX_XML)));
assertThat(stringWriter.toString(), isSimilarTo(COMPLEX_XML).withNodeFilter(nodeFilter));
assertThat(XmlContent.from(stringWriter)).isSimilarTo(COMPLEX_XML, nodeFilter);
}
@Test
@@ -116,7 +117,7 @@ public abstract class AbstractStaxHandlerTestCase {
xmlReader.parse(new InputSource(new StringReader(SIMPLE_XML)));
assertThat(result, isSimilarTo(expected).withNodeFilter(nodeFilter));
assertThat(XmlContent.of(result)).isSimilarTo(expected, nodeFilter);
}
@Test
@@ -137,10 +138,9 @@ public abstract class AbstractStaxHandlerTestCase {
xmlReader.parse(new InputSource(new StringReader(SIMPLE_XML)));
assertThat(expected, isSimilarTo(result).withNodeFilter(nodeFilter));
assertThat(XmlContent.of(result)).isSimilarTo(expected, nodeFilter);
}
protected abstract AbstractStaxHandler createStaxHandler(Result result) throws XMLStreamException;
}

View File

@@ -27,8 +27,9 @@ import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
import org.springframework.tests.XmlContent;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link DomContentHandler}.
@@ -77,7 +78,7 @@ public class DomContentHandlerTests {
expected = documentBuilder.parse(new InputSource(new StringReader(XML_1)));
xmlReader.setContentHandler(handler);
xmlReader.parse(new InputSource(new StringReader(XML_1)));
assertThat("Invalid result", result, isSimilarTo(expected));
assertThat(XmlContent.of(result)).as("Invalid result").isSimilarTo(expected);
}
@Test
@@ -86,7 +87,7 @@ public class DomContentHandlerTests {
expected = documentBuilder.parse(new InputSource(new StringReader(XML_1)));
xmlReader.setContentHandler(handler);
xmlReader.parse(new InputSource(new StringReader(XML_1)));
assertThat("Invalid result", result, isSimilarTo(expected));
assertThat(XmlContent.of(result)).as("Invalid result").isSimilarTo(expected);
}
@Test
@@ -97,7 +98,7 @@ public class DomContentHandlerTests {
expected = documentBuilder.parse(new InputSource(new StringReader(XML_2_EXPECTED)));
xmlReader.setContentHandler(handler);
xmlReader.parse(new InputSource(new StringReader(XML_2_SNIPPET)));
assertThat("Invalid result", result, isSimilarTo(expected));
assertThat(XmlContent.of(result)).as("Invalid result").isSimilarTo(expected);
}
}

View File

@@ -29,14 +29,15 @@ import javax.xml.stream.events.XMLEvent;
import org.junit.Test;
import org.springframework.tests.XmlContent;
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.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
/**
* @author Arjen Poutsma
@@ -60,7 +61,7 @@ public class ListBasedXMLEventReaderTests {
XMLEventWriter writer = this.outputFactory.createXMLEventWriter(resultWriter);
writer.add(reader);
assertThat(resultWriter.toString(), isSimilarTo(xml));
assertThat(XmlContent.from(resultWriter)).isSimilarTo(xml);
}
@Test

View File

@@ -16,20 +16,17 @@
package org.springframework.util.xml;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.xml.XMLConstants;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* @author Arjen Poutsma
@@ -56,23 +53,29 @@ public class SimpleNamespaceContextTests {
@Test
public void getNamespaceURI() {
context.bindNamespaceUri(XMLConstants.XMLNS_ATTRIBUTE, additionalNamespaceUri);
assertThat("Always returns \"http://www.w3.org/2000/xmlns/\" for \"xmlns\"",
context.getNamespaceURI(XMLConstants.XMLNS_ATTRIBUTE), is(XMLConstants.XMLNS_ATTRIBUTE_NS_URI));
assertThat(context.getNamespaceURI(XMLConstants.XMLNS_ATTRIBUTE))
.as("Always returns \"http://www.w3.org/2000/xmlns/\" for \"xmlns\"")
.isEqualTo(XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
context.bindNamespaceUri(XMLConstants.XML_NS_PREFIX, additionalNamespaceUri);
assertThat("Always returns \"http://www.w3.org/XML/1998/namespace\" for \"xml\"",
context.getNamespaceURI(XMLConstants.XML_NS_PREFIX), is(XMLConstants.XML_NS_URI));
assertThat(context.getNamespaceURI(XMLConstants.XML_NS_PREFIX))
.as("Always returns \"http://www.w3.org/XML/1998/namespace\" for \"xml\"")
.isEqualTo(XMLConstants.XML_NS_URI);
assertThat("Returns \"\" for an unbound prefix", context.getNamespaceURI(unboundPrefix),
is(XMLConstants.NULL_NS_URI));
assertThat(context.getNamespaceURI(unboundPrefix))
.as("Returns \"\" for an unbound prefix")
.isEqualTo(XMLConstants.NULL_NS_URI);
context.bindNamespaceUri(prefix, namespaceUri);
assertThat("Returns the bound namespace URI for a bound prefix", context.getNamespaceURI(prefix),
is(namespaceUri));
assertThat(context.getNamespaceURI(prefix))
.as("Returns the bound namespace URI for a bound prefix")
.isEqualTo(namespaceUri);
assertThat("By default returns URI \"\" for the default namespace prefix",
context.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX), is(XMLConstants.NULL_NS_URI));
assertThat(context.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX))
.as("By default returns URI \"\" for the default namespace prefix")
.isEqualTo(XMLConstants.NULL_NS_URI);
context.bindDefaultNamespaceUri(defaultNamespaceUri);
assertThat("Returns the set URI for the default namespace prefix",
context.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX), is(defaultNamespaceUri));
assertThat(context.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX))
.as("Returns the set URI for the default namespace prefix")
.isEqualTo(defaultNamespaceUri);
}
@Test
@@ -83,17 +86,19 @@ public class SimpleNamespaceContextTests {
@Test
public void getPrefix() {
assertThat("Always returns \"xmlns\" for \"http://www.w3.org/2000/xmlns/\"",
context.getPrefix(XMLConstants.XMLNS_ATTRIBUTE_NS_URI), is(XMLConstants.XMLNS_ATTRIBUTE));
assertThat("Always returns \"xml\" for \"http://www.w3.org/XML/1998/namespace\"",
context.getPrefix(XMLConstants.XML_NS_URI), is(XMLConstants.XML_NS_PREFIX));
assertThat(context.getPrefix(XMLConstants.XMLNS_ATTRIBUTE_NS_URI))
.as("Always returns \"xmlns\" for \"http://www.w3.org/2000/xmlns/\"")
.isEqualTo(XMLConstants.XMLNS_ATTRIBUTE);
assertThat(context.getPrefix(XMLConstants.XML_NS_URI))
.as("Always returns \"xml\" for \"http://www.w3.org/XML/1998/namespace\"")
.isEqualTo(XMLConstants.XML_NS_PREFIX);
assertThat("Returns null for an unbound namespace URI", context.getPrefix(unboundNamespaceUri),
is(nullValue()));
assertThat(context.getPrefix(unboundNamespaceUri)).as("Returns null for an unbound namespace URI").isNull();
context.bindNamespaceUri("prefix1", namespaceUri);
context.bindNamespaceUri("prefix2", namespaceUri);
assertThat("Returns a prefix for a bound namespace URI", context.getPrefix(namespaceUri),
anyOf(is("prefix1"), is("prefix2")));
assertThat(context.getPrefix(namespaceUri))
.as("Returns a prefix for a bound namespace URI")
.matches(prefix -> "prefix1".equals(prefix) || "prefix2".equals(prefix));
}
@Test
@@ -112,18 +117,21 @@ public class SimpleNamespaceContextTests {
@Test
public void getPrefixes() {
assertThat("Returns only \"xmlns\" for \"http://www.w3.org/2000/xmlns/\"",
getItemSet(context.getPrefixes(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)),
is(makeSet(XMLConstants.XMLNS_ATTRIBUTE)));
assertThat("Returns only \"xml\" for \"http://www.w3.org/XML/1998/namespace\"",
getItemSet(context.getPrefixes(XMLConstants.XML_NS_URI)), is(makeSet(XMLConstants.XML_NS_PREFIX)));
assertThat(getItemSet(context.getPrefixes(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)))
.as("Returns only \"xmlns\" for \"http://www.w3.org/2000/xmlns/\"")
.containsExactly(XMLConstants.XMLNS_ATTRIBUTE);
assertThat(getItemSet(context.getPrefixes(XMLConstants.XML_NS_URI)))
.as("Returns only \"xml\" for \"http://www.w3.org/XML/1998/namespace\"")
.containsExactly(XMLConstants.XML_NS_PREFIX);
assertThat("Returns empty iterator for unbound prefix", context.getPrefixes("unbound Namespace URI").hasNext(),
is(false));
assertThat(context.getPrefixes("unbound Namespace URI").hasNext())
.as("Returns empty iterator for unbound prefix")
.isFalse();
context.bindNamespaceUri("prefix1", namespaceUri);
context.bindNamespaceUri("prefix2", namespaceUri);
assertThat("Returns all prefixes (and only those) bound to the namespace URI",
getItemSet(context.getPrefixes(namespaceUri)), is(makeSet("prefix1", "prefix2")));
assertThat(getItemSet(context.getPrefixes(namespaceUri)))
.as("Returns all prefixes (and only those) bound to the namespace URI")
.containsExactlyInAnyOrder("prefix1", "prefix2");
}
@Test
@@ -141,9 +149,12 @@ public class SimpleNamespaceContextTests {
@Test
public void bindNamespaceUri() {
context.bindNamespaceUri(prefix, namespaceUri);
assertThat("The Namespace URI was bound to the prefix", context.getNamespaceURI(prefix), is(namespaceUri));
assertThat("The prefix was bound to the namespace URI", getItemSet(context.getPrefixes(namespaceUri)),
hasItem(prefix));
assertThat(context.getNamespaceURI(prefix))
.as("The Namespace URI was bound to the prefix")
.isEqualTo(namespaceUri);
assertThat(getItemSet(context.getPrefixes(namespaceUri)))
.as("The prefix was bound to the namespace URI")
.contains(prefix);
}
@Test
@@ -151,8 +162,9 @@ public class SimpleNamespaceContextTests {
context.bindNamespaceUri("prefix1", namespaceUri);
context.bindNamespaceUri("prefix2", namespaceUri);
context.bindNamespaceUri("prefix3", additionalNamespaceUri);
assertThat("Returns all bound prefixes", getItemSet(context.getBoundPrefixes()),
is(makeSet("prefix1", "prefix2", "prefix3")));
assertThat(getItemSet(context.getBoundPrefixes()))
.as("Returns all bound prefixes")
.containsExactlyInAnyOrder("prefix1", "prefix2", "prefix3");
}
@Test
@@ -161,8 +173,8 @@ public class SimpleNamespaceContextTests {
context.bindNamespaceUri("prefix2", namespaceUri);
context.bindNamespaceUri("prefix3", additionalNamespaceUri);
context.clear();
assertThat("All bound prefixes were removed", context.getBoundPrefixes().hasNext(), is(false));
assertThat("All bound namespace URIs were removed", context.getPrefixes(namespaceUri).hasNext(), is(false));
assertThat(context.getBoundPrefixes().hasNext()).as("All bound prefixes were removed").isFalse();
assertThat(context.getPrefixes(namespaceUri).hasNext()).as("All bound namespace URIs were removed").isFalse();
}
@Test
@@ -171,37 +183,24 @@ public class SimpleNamespaceContextTests {
context.bindNamespaceUri(prefix, namespaceUri);
context.removeBinding(prefix);
assertThat("Returns default namespace URI for removed prefix", context.getNamespaceURI(prefix),
is(XMLConstants.NULL_NS_URI));
assertThat("#getPrefix returns null when all prefixes for a namespace URI were removed",
context.getPrefix(namespaceUri), is(nullValue()));
assertThat("#getPrefixes returns an empty iterator when all prefixes for a namespace URI were removed",
context.getPrefixes(namespaceUri).hasNext(), is(false));
assertThat(context.getNamespaceURI(prefix)).as("Returns default namespace URI for removed prefix").isEqualTo(XMLConstants.NULL_NS_URI);
assertThat(context.getPrefix(namespaceUri)).as("#getPrefix returns null when all prefixes for a namespace URI were removed").isNull();
assertThat(context.getPrefixes(namespaceUri).hasNext()).as("#getPrefixes returns an empty iterator when all prefixes for a namespace URI were removed").isFalse();
context.bindNamespaceUri("prefix1", additionalNamespaceUri);
context.bindNamespaceUri("prefix2", additionalNamespaceUri);
context.removeBinding("prefix1");
assertThat("Prefix was unbound", context.getNamespaceURI("prefix1"), is(XMLConstants.NULL_NS_URI));
assertThat("#getPrefix returns a bound prefix after removal of another prefix for the same namespace URI",
context.getPrefix(additionalNamespaceUri), is("prefix2"));
assertThat("Prefix was removed from namespace URI", getItemSet(context.getPrefixes(additionalNamespaceUri)),
is(makeSet("prefix2")));
assertThat(context.getNamespaceURI("prefix1")).as("Prefix was unbound").isEqualTo(XMLConstants.NULL_NS_URI);
assertThat(context.getPrefix(additionalNamespaceUri)).as("#getPrefix returns a bound prefix after removal of another prefix for the same namespace URI").isEqualTo("prefix2");
assertThat(getItemSet(context.getPrefixes(additionalNamespaceUri)))
.as("Prefix was removed from namespace URI")
.containsExactly("prefix2");
}
private Set<String> getItemSet(Iterator<String> iterator) {
Set<String> itemSet = new HashSet<>();
while (iterator.hasNext()) {
itemSet.add(iterator.next());
}
return itemSet;
}
private Set<String> makeSet(String... items) {
Set<String> itemSet = new HashSet<>();
for (String item : items) {
itemSet.add(item);
}
Set<String> itemSet = new LinkedHashSet<>();
iterator.forEachRemaining(itemSet::add);
return itemSet;
}

View File

@@ -30,10 +30,11 @@ import javax.xml.transform.stream.StreamSource;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import org.springframework.tests.XmlContent;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
/**
* @author Arjen Poutsma
@@ -63,7 +64,7 @@ public class StaxResultTests {
assertEquals("Invalid streamWriter returned", streamWriter, result.getXMLStreamWriter());
assertNull("EventWriter returned", result.getXMLEventWriter());
transformer.transform(source, result);
assertThat("Invalid result", stringWriter.toString(), isSimilarTo(XML));
assertThat(XmlContent.from(stringWriter)).as("Invalid result").isSimilarTo(XML);
}
@Test
@@ -76,7 +77,7 @@ public class StaxResultTests {
assertEquals("Invalid eventWriter returned", eventWriter, result.getXMLEventWriter());
assertNull("StreamWriter returned", result.getXMLStreamWriter());
transformer.transform(source, result);
assertThat("Invalid result", stringWriter.toString(), isSimilarTo(XML));
assertThat(XmlContent.from(stringWriter)).as("Invalid result").isSimilarTo(XML);
}
}

View File

@@ -33,10 +33,11 @@ import org.junit.Test;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import static org.hamcrest.MatcherAssert.assertThat;
import org.springframework.tests.XmlContent;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
/**
* @author Arjen Poutsma
@@ -69,7 +70,7 @@ public class StaxSourceTests {
assertNull("EventReader returned", source.getXMLEventReader());
StringWriter writer = new StringWriter();
transformer.transform(source, new StreamResult(writer));
assertThat("Invalid result", writer.toString(), isSimilarTo(XML));
assertThat(XmlContent.from(writer)).as("Invalid result").isSimilarTo(XML);
}
@Test
@@ -82,7 +83,7 @@ public class StaxSourceTests {
Document expected = documentBuilder.parse(new InputSource(new StringReader(XML)));
Document result = documentBuilder.newDocument();
transformer.transform(source, new DOMResult(result));
assertThat("Invalid result", result, isSimilarTo(expected));
assertThat(XmlContent.of(result)).as("Invalid result").isSimilarTo(expected);
}
@Test
@@ -93,7 +94,7 @@ public class StaxSourceTests {
assertNull("StreamReader returned", source.getXMLStreamReader());
StringWriter writer = new StringWriter();
transformer.transform(source, new StreamResult(writer));
assertThat("Invalid result", writer.toString(), isSimilarTo(XML));
assertThat(XmlContent.from(writer)).as("Invalid result").isSimilarTo(XML);
}
@Test
@@ -106,6 +107,6 @@ public class StaxSourceTests {
Document expected = documentBuilder.parse(new InputSource(new StringReader(XML)));
Document result = documentBuilder.newDocument();
transformer.transform(source, new DOMResult(result));
assertThat("Invalid result", result, isSimilarTo(expected));
assertThat(XmlContent.of(result)).as("Invalid result").isSimilarTo(expected);
}
}

View File

@@ -30,8 +30,9 @@ import org.junit.Test;
import org.w3c.dom.Node;
import org.xmlunit.util.Predicate;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
import org.springframework.tests.XmlContent;
import static org.assertj.core.api.Assertions.assertThat;
public class XMLEventStreamReaderTests {
@@ -63,7 +64,7 @@ public class XMLEventStreamReaderTests {
transformer.transform(source, new StreamResult(writer));
Predicate<Node> nodeFilter = n ->
n.getNodeType() != Node.DOCUMENT_TYPE_NODE && n.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE;
assertThat(writer.toString(), isSimilarTo(XML).withNodeFilter(nodeFilter));
assertThat(XmlContent.from(writer)).isSimilarTo(XML, nodeFilter);
}
}

View File

@@ -26,8 +26,9 @@ import org.junit.Test;
import org.w3c.dom.Node;
import org.xmlunit.util.Predicate;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
import org.springframework.tests.XmlContent;
import static org.assertj.core.api.Assertions.assertThat;
public class XMLEventStreamWriterTests {
@@ -61,7 +62,7 @@ public class XMLEventStreamWriterTests {
streamWriter.writeEndDocument();
Predicate<Node> nodeFilter = n -> n.getNodeType() != Node.DOCUMENT_TYPE_NODE && n.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE;
assertThat(stringWriter.toString(), isSimilarTo(XML).withNodeFilter(nodeFilter));
assertThat(XmlContent.from(stringWriter)).isSimilarTo(XML, nodeFilter);
}