Migrate JUnit 4 assertions to AssertJ

Migrate all existing JUnit 4 `assert...` based assertions to AssertJ
and add a checkstyle rule to ensure they don't return.

See gh-23022
This commit is contained in:
Phillip Webb
2019-05-23 15:51:39 -07:00
parent 95a9d46a87
commit 9d74da006c
1636 changed files with 37861 additions and 40390 deletions

View File

@@ -20,9 +20,7 @@ import java.util.Arrays;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Harrop
@@ -40,22 +38,22 @@ public class AttributeAccessorSupportTests {
@Test
public void setAndGet() throws Exception {
this.attributeAccessor.setAttribute(NAME, VALUE);
assertEquals(VALUE, this.attributeAccessor.getAttribute(NAME));
assertThat(this.attributeAccessor.getAttribute(NAME)).isEqualTo(VALUE);
}
@Test
public void setAndHas() throws Exception {
assertFalse(this.attributeAccessor.hasAttribute(NAME));
assertThat(this.attributeAccessor.hasAttribute(NAME)).isFalse();
this.attributeAccessor.setAttribute(NAME, VALUE);
assertTrue(this.attributeAccessor.hasAttribute(NAME));
assertThat(this.attributeAccessor.hasAttribute(NAME)).isTrue();
}
@Test
public void remove() throws Exception {
assertFalse(this.attributeAccessor.hasAttribute(NAME));
assertThat(this.attributeAccessor.hasAttribute(NAME)).isFalse();
this.attributeAccessor.setAttribute(NAME, VALUE);
assertEquals(VALUE, this.attributeAccessor.removeAttribute(NAME));
assertFalse(this.attributeAccessor.hasAttribute(NAME));
assertThat(this.attributeAccessor.removeAttribute(NAME)).isEqualTo(VALUE);
assertThat(this.attributeAccessor.hasAttribute(NAME)).isFalse();
}
@Test
@@ -64,8 +62,8 @@ public class AttributeAccessorSupportTests {
this.attributeAccessor.setAttribute("abc", "123");
String[] attributeNames = this.attributeAccessor.attributeNames();
Arrays.sort(attributeNames);
assertTrue(Arrays.binarySearch(attributeNames, NAME) > -1);
assertTrue(Arrays.binarySearch(attributeNames, "abc") > -1);
assertThat(Arrays.binarySearch(attributeNames, NAME) > -1).isTrue();
assertThat(Arrays.binarySearch(attributeNames, "abc") > -1).isTrue();
}
@SuppressWarnings("serial")

View File

@@ -32,11 +32,7 @@ import org.junit.Test;
import org.springframework.util.ReflectionUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Harrop
@@ -61,33 +57,33 @@ public class BridgeMethodResolverTests {
public void testFindBridgedMethod() throws Exception {
Method unbridged = MyFoo.class.getDeclaredMethod("someMethod", String.class, Object.class);
Method bridged = MyFoo.class.getDeclaredMethod("someMethod", Serializable.class, Object.class);
assertFalse(unbridged.isBridge());
assertTrue(bridged.isBridge());
assertThat(unbridged.isBridge()).isFalse();
assertThat(bridged.isBridge()).isTrue();
assertEquals("Unbridged method not returned directly", unbridged, BridgeMethodResolver.findBridgedMethod(unbridged));
assertEquals("Incorrect bridged method returned", unbridged, BridgeMethodResolver.findBridgedMethod(bridged));
assertThat(BridgeMethodResolver.findBridgedMethod(unbridged)).as("Unbridged method not returned directly").isEqualTo(unbridged);
assertThat(BridgeMethodResolver.findBridgedMethod(bridged)).as("Incorrect bridged method returned").isEqualTo(unbridged);
}
@Test
public void testFindBridgedVarargMethod() throws Exception {
Method unbridged = MyFoo.class.getDeclaredMethod("someVarargMethod", String.class, Object[].class);
Method bridged = MyFoo.class.getDeclaredMethod("someVarargMethod", Serializable.class, Object[].class);
assertFalse(unbridged.isBridge());
assertTrue(bridged.isBridge());
assertThat(unbridged.isBridge()).isFalse();
assertThat(bridged.isBridge()).isTrue();
assertEquals("Unbridged method not returned directly", unbridged, BridgeMethodResolver.findBridgedMethod(unbridged));
assertEquals("Incorrect bridged method returned", unbridged, BridgeMethodResolver.findBridgedMethod(bridged));
assertThat(BridgeMethodResolver.findBridgedMethod(unbridged)).as("Unbridged method not returned directly").isEqualTo(unbridged);
assertThat(BridgeMethodResolver.findBridgedMethod(bridged)).as("Incorrect bridged method returned").isEqualTo(unbridged);
}
@Test
public void testFindBridgedMethodInHierarchy() throws Exception {
Method bridgeMethod = DateAdder.class.getMethod("add", Object.class);
assertTrue(bridgeMethod.isBridge());
assertThat(bridgeMethod.isBridge()).isTrue();
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(bridgeMethod);
assertFalse(bridgedMethod.isBridge());
assertEquals("add", bridgedMethod.getName());
assertEquals(1, bridgedMethod.getParameterCount());
assertEquals(Date.class, bridgedMethod.getParameterTypes()[0]);
assertThat(bridgedMethod.isBridge()).isFalse();
assertThat(bridgedMethod.getName()).isEqualTo("add");
assertThat(bridgedMethod.getParameterCount()).isEqualTo(1);
assertThat(bridgedMethod.getParameterTypes()[0]).isEqualTo(Date.class);
}
@Test
@@ -96,8 +92,8 @@ public class BridgeMethodResolverTests {
Method other = MyBar.class.getDeclaredMethod("someMethod", Integer.class, Object.class);
Method bridge = MyBar.class.getDeclaredMethod("someMethod", Object.class, Object.class);
assertTrue("Should be bridge method", BridgeMethodResolver.isBridgeMethodFor(bridge, bridged, MyBar.class));
assertFalse("Should not be bridge method", BridgeMethodResolver.isBridgeMethodFor(bridge, other, MyBar.class));
assertThat(BridgeMethodResolver.isBridgeMethodFor(bridge, bridged, MyBar.class)).as("Should be bridge method").isTrue();
assertThat(BridgeMethodResolver.isBridgeMethodFor(bridge, other, MyBar.class)).as("Should not be bridge method").isFalse();
}
@Test
@@ -108,51 +104,51 @@ public class BridgeMethodResolverTests {
Method stringFoo = MyBoo.class.getDeclaredMethod("foo", String.class);
Method integerFoo = MyBoo.class.getDeclaredMethod("foo", Integer.class);
assertEquals("foo(String) not resolved.", stringFoo, BridgeMethodResolver.findBridgedMethod(objectBridge));
assertEquals("foo(Integer) not resolved.", integerFoo, BridgeMethodResolver.findBridgedMethod(serializableBridge));
assertThat(BridgeMethodResolver.findBridgedMethod(objectBridge)).as("foo(String) not resolved.").isEqualTo(stringFoo);
assertThat(BridgeMethodResolver.findBridgedMethod(serializableBridge)).as("foo(Integer) not resolved.").isEqualTo(integerFoo);
}
@Test
public void testFindBridgedMethodFromMultipleBridges() throws Exception {
Method loadWithObjectReturn = findMethodWithReturnType("load", Object.class, SettingsDaoImpl.class);
assertNotNull(loadWithObjectReturn);
assertThat(loadWithObjectReturn).isNotNull();
Method loadWithSettingsReturn = findMethodWithReturnType("load", Settings.class, SettingsDaoImpl.class);
assertNotNull(loadWithSettingsReturn);
assertNotSame(loadWithObjectReturn, loadWithSettingsReturn);
assertThat(loadWithSettingsReturn).isNotNull();
assertThat(loadWithSettingsReturn).isNotSameAs(loadWithObjectReturn);
Method method = SettingsDaoImpl.class.getMethod("load");
assertEquals(method, BridgeMethodResolver.findBridgedMethod(loadWithObjectReturn));
assertEquals(method, BridgeMethodResolver.findBridgedMethod(loadWithSettingsReturn));
assertThat(BridgeMethodResolver.findBridgedMethod(loadWithObjectReturn)).isEqualTo(method);
assertThat(BridgeMethodResolver.findBridgedMethod(loadWithSettingsReturn)).isEqualTo(method);
}
@Test
public void testFindBridgedMethodFromParent() throws Exception {
Method loadFromParentBridge = SettingsDaoImpl.class.getMethod("loadFromParent");
assertTrue(loadFromParentBridge.isBridge());
assertThat(loadFromParentBridge.isBridge()).isTrue();
Method loadFromParent = AbstractDaoImpl.class.getMethod("loadFromParent");
assertFalse(loadFromParent.isBridge());
assertThat(loadFromParent.isBridge()).isFalse();
assertEquals(loadFromParent, BridgeMethodResolver.findBridgedMethod(loadFromParentBridge));
assertThat(BridgeMethodResolver.findBridgedMethod(loadFromParentBridge)).isEqualTo(loadFromParent);
}
@Test
public void testWithSingleBoundParameterizedOnInstantiate() throws Exception {
Method bridgeMethod = DelayQueue.class.getMethod("add", Object.class);
assertTrue(bridgeMethod.isBridge());
assertThat(bridgeMethod.isBridge()).isTrue();
Method actualMethod = DelayQueue.class.getMethod("add", Delayed.class);
assertFalse(actualMethod.isBridge());
assertEquals(actualMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod));
assertThat(actualMethod.isBridge()).isFalse();
assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(actualMethod);
}
@Test
public void testWithDoubleBoundParameterizedOnInstantiate() throws Exception {
Method bridgeMethod = SerializableBounded.class.getMethod("boundedOperation", Object.class);
assertTrue(bridgeMethod.isBridge());
assertThat(bridgeMethod.isBridge()).isTrue();
Method actualMethod = SerializableBounded.class.getMethod("boundedOperation", HashMap.class);
assertFalse(actualMethod.isBridge());
assertEquals(actualMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod));
assertThat(actualMethod.isBridge()).isFalse();
assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(actualMethod);
}
@Test
@@ -170,33 +166,34 @@ public class BridgeMethodResolverTests {
}
}
}
assertTrue(bridgeMethod != null && bridgeMethod.isBridge());
assertTrue(bridgedMethod != null && !bridgedMethod.isBridge());
assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod));
assertThat(bridgeMethod != null && bridgeMethod.isBridge()).isTrue();
boolean condition = bridgedMethod != null && !bridgedMethod.isBridge();
assertThat(condition).isTrue();
assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod);
}
@Test
public void testOnAllMethods() throws Exception {
Method[] methods = StringList.class.getMethods();
for (Method method : methods) {
assertNotNull(BridgeMethodResolver.findBridgedMethod(method));
assertThat(BridgeMethodResolver.findBridgedMethod(method)).isNotNull();
}
}
@Test
public void testSPR2583() throws Exception {
Method bridgedMethod = MessageBroadcasterImpl.class.getMethod("receive", MessageEvent.class);
assertFalse(bridgedMethod.isBridge());
assertThat(bridgedMethod.isBridge()).isFalse();
Method bridgeMethod = MessageBroadcasterImpl.class.getMethod("receive", Event.class);
assertTrue(bridgeMethod.isBridge());
assertThat(bridgeMethod.isBridge()).isTrue();
Method otherMethod = MessageBroadcasterImpl.class.getMethod("receive", NewMessageEvent.class);
assertFalse(otherMethod.isBridge());
assertThat(otherMethod.isBridge()).isFalse();
assertFalse("Match identified incorrectly", BridgeMethodResolver.isBridgeMethodFor(bridgeMethod, otherMethod, MessageBroadcasterImpl.class));
assertTrue("Match not found correctly", BridgeMethodResolver.isBridgeMethodFor(bridgeMethod, bridgedMethod, MessageBroadcasterImpl.class));
assertThat(BridgeMethodResolver.isBridgeMethodFor(bridgeMethod, otherMethod, MessageBroadcasterImpl.class)).as("Match identified incorrectly").isFalse();
assertThat(BridgeMethodResolver.isBridgeMethodFor(bridgeMethod, bridgedMethod, MessageBroadcasterImpl.class)).as("Match not found correctly").isTrue();
assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod));
assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod);
}
@Test
@@ -205,106 +202,106 @@ public class BridgeMethodResolverTests {
Method abstractBoundedFoo = YourHomer.class.getDeclaredMethod("foo", AbstractBounded.class);
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(objectBridge);
assertEquals("foo(AbstractBounded) not resolved.", abstractBoundedFoo, bridgedMethod);
assertThat(bridgedMethod).as("foo(AbstractBounded) not resolved.").isEqualTo(abstractBoundedFoo);
}
@Test
public void testSPR2648() throws Exception {
Method bridgeMethod = ReflectionUtils.findMethod(GenericSqlMapIntegerDao.class, "saveOrUpdate", Object.class);
assertTrue(bridgeMethod != null && bridgeMethod.isBridge());
assertThat(bridgeMethod != null && bridgeMethod.isBridge()).isTrue();
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(bridgeMethod);
assertFalse(bridgedMethod.isBridge());
assertEquals("saveOrUpdate", bridgedMethod.getName());
assertThat(bridgedMethod.isBridge()).isFalse();
assertThat(bridgedMethod.getName()).isEqualTo("saveOrUpdate");
}
@Test
public void testSPR2763() throws Exception {
Method bridgedMethod = AbstractDao.class.getDeclaredMethod("save", Object.class);
assertFalse(bridgedMethod.isBridge());
assertThat(bridgedMethod.isBridge()).isFalse();
Method bridgeMethod = UserDaoImpl.class.getDeclaredMethod("save", User.class);
assertTrue(bridgeMethod.isBridge());
assertThat(bridgeMethod.isBridge()).isTrue();
assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod));
assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod);
}
@Test
public void testSPR3041() throws Exception {
Method bridgedMethod = BusinessDao.class.getDeclaredMethod("save", Business.class);
assertFalse(bridgedMethod.isBridge());
assertThat(bridgedMethod.isBridge()).isFalse();
Method bridgeMethod = BusinessDao.class.getDeclaredMethod("save", Object.class);
assertTrue(bridgeMethod.isBridge());
assertThat(bridgeMethod.isBridge()).isTrue();
assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod));
assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod);
}
@Test
public void testSPR3173() throws Exception {
Method bridgedMethod = UserDaoImpl.class.getDeclaredMethod("saveVararg", User.class, Object[].class);
assertFalse(bridgedMethod.isBridge());
assertThat(bridgedMethod.isBridge()).isFalse();
Method bridgeMethod = UserDaoImpl.class.getDeclaredMethod("saveVararg", Object.class, Object[].class);
assertTrue(bridgeMethod.isBridge());
assertThat(bridgeMethod.isBridge()).isTrue();
assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod));
assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod);
}
@Test
public void testSPR3304() throws Exception {
Method bridgedMethod = MegaMessageProducerImpl.class.getDeclaredMethod("receive", MegaMessageEvent.class);
assertFalse(bridgedMethod.isBridge());
assertThat(bridgedMethod.isBridge()).isFalse();
Method bridgeMethod = MegaMessageProducerImpl.class.getDeclaredMethod("receive", MegaEvent.class);
assertTrue(bridgeMethod.isBridge());
assertThat(bridgeMethod.isBridge()).isTrue();
assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod));
assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod);
}
@Test
public void testSPR3324() throws Exception {
Method bridgedMethod = BusinessDao.class.getDeclaredMethod("get", Long.class);
assertFalse(bridgedMethod.isBridge());
assertThat(bridgedMethod.isBridge()).isFalse();
Method bridgeMethod = BusinessDao.class.getDeclaredMethod("get", Object.class);
assertTrue(bridgeMethod.isBridge());
assertThat(bridgeMethod.isBridge()).isTrue();
assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod));
assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod);
}
@Test
public void testSPR3357() throws Exception {
Method bridgedMethod = ExtendsAbstractImplementsInterface.class.getDeclaredMethod(
"doSomething", DomainObjectExtendsSuper.class, Object.class);
assertFalse(bridgedMethod.isBridge());
assertThat(bridgedMethod.isBridge()).isFalse();
Method bridgeMethod = ExtendsAbstractImplementsInterface.class.getDeclaredMethod(
"doSomething", DomainObjectSuper.class, Object.class);
assertTrue(bridgeMethod.isBridge());
assertThat(bridgeMethod.isBridge()).isTrue();
assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod));
assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod);
}
@Test
public void testSPR3485() throws Exception {
Method bridgedMethod = DomainObject.class.getDeclaredMethod(
"method2", ParameterType.class, byte[].class);
assertFalse(bridgedMethod.isBridge());
assertThat(bridgedMethod.isBridge()).isFalse();
Method bridgeMethod = DomainObject.class.getDeclaredMethod(
"method2", Serializable.class, Object.class);
assertTrue(bridgeMethod.isBridge());
assertThat(bridgeMethod.isBridge()).isTrue();
assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod));
assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod);
}
@Test
public void testSPR3534() throws Exception {
Method bridgeMethod = ReflectionUtils.findMethod(TestEmailProvider.class, "findBy", Object.class);
assertTrue(bridgeMethod != null && bridgeMethod.isBridge());
assertThat(bridgeMethod != null && bridgeMethod.isBridge()).isTrue();
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(bridgeMethod);
assertFalse(bridgedMethod.isBridge());
assertEquals("findBy", bridgedMethod.getName());
assertThat(bridgedMethod.isBridge()).isFalse();
assertThat(bridgedMethod.getName()).isEqualTo("findBy");
}
@Test // SPR-16103
@@ -321,7 +318,7 @@ public class BridgeMethodResolverTests {
for (Method method : clazz.getDeclaredMethods()){
Method bridged = BridgeMethodResolver.findBridgedMethod(method);
Method expected = clazz.getMethod("test", FooEntity.class);
assertEquals(expected, bridged);
assertThat(bridged).isEqualTo(expected);
}
}

View File

@@ -21,11 +21,9 @@ import java.util.Set;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Rod Johnson
@@ -38,17 +36,17 @@ public class ConstantsTests {
@Test
public void constants() {
Constants c = new Constants(A.class);
assertEquals(A.class.getName(), c.getClassName());
assertEquals(9, c.getSize());
assertThat(c.getClassName()).isEqualTo(A.class.getName());
assertThat(c.getSize()).isEqualTo(9);
assertEquals(A.DOG, c.asNumber("DOG").intValue());
assertEquals(A.DOG, c.asNumber("dog").intValue());
assertEquals(A.CAT, c.asNumber("cat").intValue());
assertThat(c.asNumber("DOG").intValue()).isEqualTo(A.DOG);
assertThat(c.asNumber("dog").intValue()).isEqualTo(A.DOG);
assertThat(c.asNumber("cat").intValue()).isEqualTo(A.CAT);
assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() ->
c.asNumber("bogus"));
assertTrue(c.asString("S1").equals(A.S1));
assertThat(c.asString("S1").equals(A.S1)).isTrue();
assertThatExceptionOfType(Constants.ConstantException.class).as("wrong type").isThrownBy(() ->
c.asNumber("S1"));
}
@@ -58,18 +56,18 @@ public class ConstantsTests {
Constants c = new Constants(A.class);
Set<?> names = c.getNames("");
assertEquals(c.getSize(), names.size());
assertTrue(names.contains("DOG"));
assertTrue(names.contains("CAT"));
assertTrue(names.contains("S1"));
assertThat(names.size()).isEqualTo(c.getSize());
assertThat(names.contains("DOG")).isTrue();
assertThat(names.contains("CAT")).isTrue();
assertThat(names.contains("S1")).isTrue();
names = c.getNames("D");
assertEquals(1, names.size());
assertTrue(names.contains("DOG"));
assertThat(names.size()).isEqualTo(1);
assertThat(names.contains("DOG")).isTrue();
names = c.getNames("d");
assertEquals(1, names.size());
assertTrue(names.contains("DOG"));
assertThat(names.size()).isEqualTo(1);
assertThat(names.contains("DOG")).isTrue();
}
@Test
@@ -77,24 +75,24 @@ public class ConstantsTests {
Constants c = new Constants(A.class);
Set<?> values = c.getValues("");
assertEquals(7, values.size());
assertTrue(values.contains(Integer.valueOf(0)));
assertTrue(values.contains(Integer.valueOf(66)));
assertTrue(values.contains(""));
assertThat(values.size()).isEqualTo(7);
assertThat(values.contains(Integer.valueOf(0))).isTrue();
assertThat(values.contains(Integer.valueOf(66))).isTrue();
assertThat(values.contains("")).isTrue();
values = c.getValues("D");
assertEquals(1, values.size());
assertTrue(values.contains(Integer.valueOf(0)));
assertThat(values.size()).isEqualTo(1);
assertThat(values.contains(Integer.valueOf(0))).isTrue();
values = c.getValues("prefix");
assertEquals(2, values.size());
assertTrue(values.contains(Integer.valueOf(1)));
assertTrue(values.contains(Integer.valueOf(2)));
assertThat(values.size()).isEqualTo(2);
assertThat(values.contains(Integer.valueOf(1))).isTrue();
assertThat(values.contains(Integer.valueOf(2))).isTrue();
values = c.getValuesForProperty("myProperty");
assertEquals(2, values.size());
assertTrue(values.contains(Integer.valueOf(1)));
assertTrue(values.contains(Integer.valueOf(2)));
assertThat(values.size()).isEqualTo(2);
assertThat(values.contains(Integer.valueOf(1))).isTrue();
assertThat(values.contains(Integer.valueOf(2))).isTrue();
}
@Test
@@ -105,24 +103,24 @@ public class ConstantsTests {
Constants c = new Constants(A.class);
Set<?> values = c.getValues("");
assertEquals(7, values.size());
assertTrue(values.contains(Integer.valueOf(0)));
assertTrue(values.contains(Integer.valueOf(66)));
assertTrue(values.contains(""));
assertThat(values.size()).isEqualTo(7);
assertThat(values.contains(Integer.valueOf(0))).isTrue();
assertThat(values.contains(Integer.valueOf(66))).isTrue();
assertThat(values.contains("")).isTrue();
values = c.getValues("D");
assertEquals(1, values.size());
assertTrue(values.contains(Integer.valueOf(0)));
assertThat(values.size()).isEqualTo(1);
assertThat(values.contains(Integer.valueOf(0))).isTrue();
values = c.getValues("prefix");
assertEquals(2, values.size());
assertTrue(values.contains(Integer.valueOf(1)));
assertTrue(values.contains(Integer.valueOf(2)));
assertThat(values.size()).isEqualTo(2);
assertThat(values.contains(Integer.valueOf(1))).isTrue();
assertThat(values.contains(Integer.valueOf(2))).isTrue();
values = c.getValuesForProperty("myProperty");
assertEquals(2, values.size());
assertTrue(values.contains(Integer.valueOf(1)));
assertTrue(values.contains(Integer.valueOf(2)));
assertThat(values.size()).isEqualTo(2);
assertThat(values.contains(Integer.valueOf(1))).isTrue();
assertThat(values.contains(Integer.valueOf(2))).isTrue();
}
finally {
Locale.setDefault(oldLocale);
@@ -134,58 +132,58 @@ public class ConstantsTests {
Constants c = new Constants(A.class);
Set<?> names = c.getNamesForSuffix("_PROPERTY");
assertEquals(2, names.size());
assertTrue(names.contains("NO_PROPERTY"));
assertTrue(names.contains("YES_PROPERTY"));
assertThat(names.size()).isEqualTo(2);
assertThat(names.contains("NO_PROPERTY")).isTrue();
assertThat(names.contains("YES_PROPERTY")).isTrue();
Set<?> values = c.getValuesForSuffix("_PROPERTY");
assertEquals(2, values.size());
assertTrue(values.contains(Integer.valueOf(3)));
assertTrue(values.contains(Integer.valueOf(4)));
assertThat(values.size()).isEqualTo(2);
assertThat(values.contains(Integer.valueOf(3))).isTrue();
assertThat(values.contains(Integer.valueOf(4))).isTrue();
}
@Test
public void toCode() {
Constants c = new Constants(A.class);
assertEquals("DOG", c.toCode(Integer.valueOf(0), ""));
assertEquals("DOG", c.toCode(Integer.valueOf(0), "D"));
assertEquals("DOG", c.toCode(Integer.valueOf(0), "DO"));
assertEquals("DOG", c.toCode(Integer.valueOf(0), "DoG"));
assertEquals("DOG", c.toCode(Integer.valueOf(0), null));
assertEquals("CAT", c.toCode(Integer.valueOf(66), ""));
assertEquals("CAT", c.toCode(Integer.valueOf(66), "C"));
assertEquals("CAT", c.toCode(Integer.valueOf(66), "ca"));
assertEquals("CAT", c.toCode(Integer.valueOf(66), "cAt"));
assertEquals("CAT", c.toCode(Integer.valueOf(66), null));
assertEquals("S1", c.toCode("", ""));
assertEquals("S1", c.toCode("", "s"));
assertEquals("S1", c.toCode("", "s1"));
assertEquals("S1", c.toCode("", null));
assertThat(c.toCode(Integer.valueOf(0), "")).isEqualTo("DOG");
assertThat(c.toCode(Integer.valueOf(0), "D")).isEqualTo("DOG");
assertThat(c.toCode(Integer.valueOf(0), "DO")).isEqualTo("DOG");
assertThat(c.toCode(Integer.valueOf(0), "DoG")).isEqualTo("DOG");
assertThat(c.toCode(Integer.valueOf(0), null)).isEqualTo("DOG");
assertThat(c.toCode(Integer.valueOf(66), "")).isEqualTo("CAT");
assertThat(c.toCode(Integer.valueOf(66), "C")).isEqualTo("CAT");
assertThat(c.toCode(Integer.valueOf(66), "ca")).isEqualTo("CAT");
assertThat(c.toCode(Integer.valueOf(66), "cAt")).isEqualTo("CAT");
assertThat(c.toCode(Integer.valueOf(66), null)).isEqualTo("CAT");
assertThat(c.toCode("", "")).isEqualTo("S1");
assertThat(c.toCode("", "s")).isEqualTo("S1");
assertThat(c.toCode("", "s1")).isEqualTo("S1");
assertThat(c.toCode("", null)).isEqualTo("S1");
assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() ->
c.toCode("bogus", "bogus"));
assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() ->
c.toCode("bogus", null));
assertEquals("MY_PROPERTY_NO", c.toCodeForProperty(Integer.valueOf(1), "myProperty"));
assertEquals("MY_PROPERTY_YES", c.toCodeForProperty(Integer.valueOf(2), "myProperty"));
assertThat(c.toCodeForProperty(Integer.valueOf(1), "myProperty")).isEqualTo("MY_PROPERTY_NO");
assertThat(c.toCodeForProperty(Integer.valueOf(2), "myProperty")).isEqualTo("MY_PROPERTY_YES");
assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() ->
c.toCodeForProperty("bogus", "bogus"));
assertEquals("DOG", c.toCodeForSuffix(Integer.valueOf(0), ""));
assertEquals("DOG", c.toCodeForSuffix(Integer.valueOf(0), "G"));
assertEquals("DOG", c.toCodeForSuffix(Integer.valueOf(0), "OG"));
assertEquals("DOG", c.toCodeForSuffix(Integer.valueOf(0), "DoG"));
assertEquals("DOG", c.toCodeForSuffix(Integer.valueOf(0), null));
assertEquals("CAT", c.toCodeForSuffix(Integer.valueOf(66), ""));
assertEquals("CAT", c.toCodeForSuffix(Integer.valueOf(66), "T"));
assertEquals("CAT", c.toCodeForSuffix(Integer.valueOf(66), "at"));
assertEquals("CAT", c.toCodeForSuffix(Integer.valueOf(66), "cAt"));
assertEquals("CAT", c.toCodeForSuffix(Integer.valueOf(66), null));
assertEquals("S1", c.toCodeForSuffix("", ""));
assertEquals("S1", c.toCodeForSuffix("", "1"));
assertEquals("S1", c.toCodeForSuffix("", "s1"));
assertEquals("S1", c.toCodeForSuffix("", null));
assertThat(c.toCodeForSuffix(Integer.valueOf(0), "")).isEqualTo("DOG");
assertThat(c.toCodeForSuffix(Integer.valueOf(0), "G")).isEqualTo("DOG");
assertThat(c.toCodeForSuffix(Integer.valueOf(0), "OG")).isEqualTo("DOG");
assertThat(c.toCodeForSuffix(Integer.valueOf(0), "DoG")).isEqualTo("DOG");
assertThat(c.toCodeForSuffix(Integer.valueOf(0), null)).isEqualTo("DOG");
assertThat(c.toCodeForSuffix(Integer.valueOf(66), "")).isEqualTo("CAT");
assertThat(c.toCodeForSuffix(Integer.valueOf(66), "T")).isEqualTo("CAT");
assertThat(c.toCodeForSuffix(Integer.valueOf(66), "at")).isEqualTo("CAT");
assertThat(c.toCodeForSuffix(Integer.valueOf(66), "cAt")).isEqualTo("CAT");
assertThat(c.toCodeForSuffix(Integer.valueOf(66), null)).isEqualTo("CAT");
assertThat(c.toCodeForSuffix("", "")).isEqualTo("S1");
assertThat(c.toCodeForSuffix("", "1")).isEqualTo("S1");
assertThat(c.toCodeForSuffix("", "s1")).isEqualTo("S1");
assertThat(c.toCodeForSuffix("", null)).isEqualTo("S1");
assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() ->
c.toCodeForSuffix("bogus", "bogus"));
assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() ->
@@ -196,30 +194,30 @@ public class ConstantsTests {
public void getValuesWithNullPrefix() throws Exception {
Constants c = new Constants(A.class);
Set<?> values = c.getValues(null);
assertEquals("Must have returned *all* public static final values", 7, values.size());
assertThat(values.size()).as("Must have returned *all* public static final values").isEqualTo(7);
}
@Test
public void getValuesWithEmptyStringPrefix() throws Exception {
Constants c = new Constants(A.class);
Set<Object> values = c.getValues("");
assertEquals("Must have returned *all* public static final values", 7, values.size());
assertThat(values.size()).as("Must have returned *all* public static final values").isEqualTo(7);
}
@Test
public void getValuesWithWhitespacedStringPrefix() throws Exception {
Constants c = new Constants(A.class);
Set<?> values = c.getValues(" ");
assertEquals("Must have returned *all* public static final values", 7, values.size());
assertThat(values.size()).as("Must have returned *all* public static final values").isEqualTo(7);
}
@Test
public void withClassThatExposesNoConstants() throws Exception {
Constants c = new Constants(NoConstants.class);
assertEquals(0, c.getSize());
assertThat(c.getSize()).isEqualTo(0);
final Set<?> values = c.getValues("");
assertNotNull(values);
assertEquals(0, values.size());
assertThat(values).isNotNull();
assertThat(values.size()).isEqualTo(0);
}
@Test

View File

@@ -32,8 +32,8 @@ import reactor.core.publisher.Mono;
import org.springframework.tests.sample.objects.TestObject;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
/**
* Unit tests for {@link Conventions}.
@@ -45,28 +45,22 @@ public class ConventionsTests {
@Test
public void simpleObject() {
assertEquals("Incorrect singular variable name",
"testObject", Conventions.getVariableName(new TestObject()));
assertEquals("Incorrect singular variable name", "testObject",
Conventions.getVariableNameForParameter(getMethodParameter(TestObject.class)));
assertEquals("Incorrect singular variable name", "testObject",
Conventions.getVariableNameForReturnType(getMethodForReturnType(TestObject.class)));
assertThat(Conventions.getVariableName(new TestObject())).as("Incorrect singular variable name").isEqualTo("testObject");
assertThat(Conventions.getVariableNameForParameter(getMethodParameter(TestObject.class))).as("Incorrect singular variable name").isEqualTo("testObject");
assertThat(Conventions.getVariableNameForReturnType(getMethodForReturnType(TestObject.class))).as("Incorrect singular variable name").isEqualTo("testObject");
}
@Test
public void array() {
assertEquals("Incorrect plural array form",
"testObjectList", Conventions.getVariableName(new TestObject[0]));
Object actual = Conventions.getVariableName(new TestObject[0]);
assertThat(actual).as("Incorrect plural array form").isEqualTo("testObjectList");
}
@Test
public void list() {
assertEquals("Incorrect plural List form", "testObjectList",
Conventions.getVariableName(Collections.singletonList(new TestObject())));
assertEquals("Incorrect plural List form", "testObjectList",
Conventions.getVariableNameForParameter(getMethodParameter(List.class)));
assertEquals("Incorrect plural List form", "testObjectList",
Conventions.getVariableNameForReturnType(getMethodForReturnType(List.class)));
assertThat(Conventions.getVariableName(Collections.singletonList(new TestObject()))).as("Incorrect plural List form").isEqualTo("testObjectList");
assertThat(Conventions.getVariableNameForParameter(getMethodParameter(List.class))).as("Incorrect plural List form").isEqualTo("testObjectList");
assertThat(Conventions.getVariableNameForReturnType(getMethodForReturnType(List.class))).as("Incorrect plural List form").isEqualTo("testObjectList");
}
@Test
@@ -77,43 +71,32 @@ public class ConventionsTests {
@Test
public void set() {
assertEquals("Incorrect plural Set form", "testObjectList",
Conventions.getVariableName(Collections.singleton(new TestObject())));
assertEquals("Incorrect plural Set form", "testObjectList",
Conventions.getVariableNameForParameter(getMethodParameter(Set.class)));
assertEquals("Incorrect plural Set form", "testObjectList",
Conventions.getVariableNameForReturnType(getMethodForReturnType(Set.class)));
assertThat(Conventions.getVariableName(Collections.singleton(new TestObject()))).as("Incorrect plural Set form").isEqualTo("testObjectList");
assertThat(Conventions.getVariableNameForParameter(getMethodParameter(Set.class))).as("Incorrect plural Set form").isEqualTo("testObjectList");
assertThat(Conventions.getVariableNameForReturnType(getMethodForReturnType(Set.class))).as("Incorrect plural Set form").isEqualTo("testObjectList");
}
@Test
public void reactiveParameters() {
assertEquals("testObjectMono",
Conventions.getVariableNameForParameter(getMethodParameter(Mono.class)));
assertEquals("testObjectFlux",
Conventions.getVariableNameForParameter(getMethodParameter(Flux.class)));
assertEquals("testObjectSingle",
Conventions.getVariableNameForParameter(getMethodParameter(Single.class)));
assertEquals("testObjectObservable",
Conventions.getVariableNameForParameter(getMethodParameter(Observable.class)));
assertThat(Conventions.getVariableNameForParameter(getMethodParameter(Mono.class))).isEqualTo("testObjectMono");
assertThat(Conventions.getVariableNameForParameter(getMethodParameter(Flux.class))).isEqualTo("testObjectFlux");
assertThat(Conventions.getVariableNameForParameter(getMethodParameter(Single.class))).isEqualTo("testObjectSingle");
assertThat(Conventions.getVariableNameForParameter(getMethodParameter(Observable.class))).isEqualTo("testObjectObservable");
}
@Test
public void reactiveReturnTypes() {
assertEquals("testObjectMono",
Conventions.getVariableNameForReturnType(getMethodForReturnType(Mono.class)));
assertEquals("testObjectFlux",
Conventions.getVariableNameForReturnType(getMethodForReturnType(Flux.class)));
assertEquals("testObjectSingle",
Conventions.getVariableNameForReturnType(getMethodForReturnType(Single.class)));
assertEquals("testObjectObservable",
Conventions.getVariableNameForReturnType(getMethodForReturnType(Observable.class)));
assertThat(Conventions.getVariableNameForReturnType(getMethodForReturnType(Mono.class))).isEqualTo("testObjectMono");
assertThat(Conventions.getVariableNameForReturnType(getMethodForReturnType(Flux.class))).isEqualTo("testObjectFlux");
assertThat(Conventions.getVariableNameForReturnType(getMethodForReturnType(Single.class))).isEqualTo("testObjectSingle");
assertThat(Conventions.getVariableNameForReturnType(getMethodForReturnType(Observable.class))).isEqualTo("testObjectObservable");
}
@Test
public void attributeNameToPropertyName() {
assertEquals("transactionManager", Conventions.attributeNameToPropertyName("transaction-manager"));
assertEquals("pointcutRef", Conventions.attributeNameToPropertyName("pointcut-ref"));
assertEquals("lookupOnStartup", Conventions.attributeNameToPropertyName("lookup-on-startup"));
assertThat(Conventions.attributeNameToPropertyName("transaction-manager")).isEqualTo("transactionManager");
assertThat(Conventions.attributeNameToPropertyName("pointcut-ref")).isEqualTo("pointcutRef");
assertThat(Conventions.attributeNameToPropertyName("lookup-on-startup")).isEqualTo("lookupOnStartup");
}
@Test
@@ -121,7 +104,7 @@ public class ConventionsTests {
String baseName = "foo";
Class<String> cls = String.class;
String desiredResult = "java.lang.String.foo";
assertEquals(desiredResult, Conventions.getQualifiedAttributeName(cls, baseName));
assertThat(Conventions.getQualifiedAttributeName(cls, baseName)).isEqualTo(desiredResult);
}

View File

@@ -20,7 +20,7 @@ import java.util.Arrays;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Juergen Hoeller
@@ -32,55 +32,55 @@ public class ExceptionDepthComparatorTests {
@Test
public void targetBeforeSameDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(TargetException.class, SameDepthException.class);
assertEquals(TargetException.class, foundClass);
assertThat(foundClass).isEqualTo(TargetException.class);
}
@Test
public void sameDepthBeforeTarget() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(SameDepthException.class, TargetException.class);
assertEquals(TargetException.class, foundClass);
assertThat(foundClass).isEqualTo(TargetException.class);
}
@Test
public void lowestDepthBeforeTarget() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(LowestDepthException.class, TargetException.class);
assertEquals(TargetException.class, foundClass);
assertThat(foundClass).isEqualTo(TargetException.class);
}
@Test
public void targetBeforeLowestDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(TargetException.class, LowestDepthException.class);
assertEquals(TargetException.class, foundClass);
assertThat(foundClass).isEqualTo(TargetException.class);
}
@Test
public void noDepthBeforeTarget() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(NoDepthException.class, TargetException.class);
assertEquals(TargetException.class, foundClass);
assertThat(foundClass).isEqualTo(TargetException.class);
}
@Test
public void noDepthBeforeHighestDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(NoDepthException.class, HighestDepthException.class);
assertEquals(HighestDepthException.class, foundClass);
assertThat(foundClass).isEqualTo(HighestDepthException.class);
}
@Test
public void highestDepthBeforeNoDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(HighestDepthException.class, NoDepthException.class);
assertEquals(HighestDepthException.class, foundClass);
assertThat(foundClass).isEqualTo(HighestDepthException.class);
}
@Test
public void highestDepthBeforeLowestDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(HighestDepthException.class, LowestDepthException.class);
assertEquals(LowestDepthException.class, foundClass);
assertThat(foundClass).isEqualTo(LowestDepthException.class);
}
@Test
public void lowestDepthBeforeHighestDepth() throws Exception {
Class<? extends Throwable> foundClass = findClosestMatch(LowestDepthException.class, HighestDepthException.class);
assertEquals(LowestDepthException.class, foundClass);
assertThat(foundClass).isEqualTo(LowestDepthException.class);
}
private Class<? extends Throwable> findClosestMatch(

View File

@@ -28,9 +28,6 @@ import java.util.Map;
import org.junit.Test;
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;
import static org.springframework.core.GenericTypeResolver.getTypeVariableMap;
import static org.springframework.core.GenericTypeResolver.resolveReturnTypeArgument;
import static org.springframework.core.GenericTypeResolver.resolveType;
@@ -46,64 +43,59 @@ public class GenericTypeResolverTests {
@Test
public void simpleInterfaceType() {
assertEquals(String.class, resolveTypeArgument(MySimpleInterfaceType.class, MyInterfaceType.class));
assertThat(resolveTypeArgument(MySimpleInterfaceType.class, MyInterfaceType.class)).isEqualTo(String.class);
}
@Test
public void simpleCollectionInterfaceType() {
assertEquals(Collection.class, resolveTypeArgument(MyCollectionInterfaceType.class, MyInterfaceType.class));
assertThat(resolveTypeArgument(MyCollectionInterfaceType.class, MyInterfaceType.class)).isEqualTo(Collection.class);
}
@Test
public void simpleSuperclassType() {
assertEquals(String.class, resolveTypeArgument(MySimpleSuperclassType.class, MySuperclassType.class));
assertThat(resolveTypeArgument(MySimpleSuperclassType.class, MySuperclassType.class)).isEqualTo(String.class);
}
@Test
public void simpleCollectionSuperclassType() {
assertEquals(Collection.class, resolveTypeArgument(MyCollectionSuperclassType.class, MySuperclassType.class));
assertThat(resolveTypeArgument(MyCollectionSuperclassType.class, MySuperclassType.class)).isEqualTo(Collection.class);
}
@Test
public void nullIfNotResolvable() {
GenericClass<String> obj = new GenericClass<>();
assertNull(resolveTypeArgument(obj.getClass(), GenericClass.class));
assertThat((Object) resolveTypeArgument(obj.getClass(), GenericClass.class)).isNull();
}
@Test
public void methodReturnTypes() {
assertEquals(Integer.class,
resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "integer"), MyInterfaceType.class));
assertEquals(String.class,
resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "string"), MyInterfaceType.class));
assertEquals(null, resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "raw"), MyInterfaceType.class));
assertEquals(null,
resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "object"), MyInterfaceType.class));
assertThat(resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "integer"), MyInterfaceType.class)).isEqualTo(Integer.class);
assertThat(resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "string"), MyInterfaceType.class)).isEqualTo(String.class);
assertThat(resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "raw"), MyInterfaceType.class)).isEqualTo(null);
assertThat(resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "object"), MyInterfaceType.class)).isEqualTo(null);
}
@Test
public void testResolveType() {
Method intMessageMethod = findMethod(MyTypeWithMethods.class, "readIntegerInputMessage", MyInterfaceType.class);
MethodParameter intMessageMethodParam = new MethodParameter(intMessageMethod, 0);
assertEquals(MyInterfaceType.class,
resolveType(intMessageMethodParam.getGenericParameterType(), new HashMap<>()));
assertThat(resolveType(intMessageMethodParam.getGenericParameterType(), new HashMap<>())).isEqualTo(MyInterfaceType.class);
Method intArrMessageMethod = findMethod(MyTypeWithMethods.class, "readIntegerArrayInputMessage",
MyInterfaceType[].class);
MethodParameter intArrMessageMethodParam = new MethodParameter(intArrMessageMethod, 0);
assertEquals(MyInterfaceType[].class,
resolveType(intArrMessageMethodParam.getGenericParameterType(), new HashMap<>()));
assertThat(resolveType(intArrMessageMethodParam.getGenericParameterType(), new HashMap<>())).isEqualTo(MyInterfaceType[].class);
Method genericArrMessageMethod = findMethod(MySimpleTypeWithMethods.class, "readGenericArrayInputMessage",
Object[].class);
MethodParameter genericArrMessageMethodParam = new MethodParameter(genericArrMessageMethod, 0);
Map<TypeVariable, Type> varMap = getTypeVariableMap(MySimpleTypeWithMethods.class);
assertEquals(Integer[].class, resolveType(genericArrMessageMethodParam.getGenericParameterType(), varMap));
assertThat(resolveType(genericArrMessageMethodParam.getGenericParameterType(), varMap)).isEqualTo(Integer[].class);
}
@Test
public void testBoundParameterizedType() {
assertEquals(B.class, resolveTypeArgument(TestImpl.class, TestIfc.class));
assertThat(resolveTypeArgument(TestImpl.class, TestIfc.class)).isEqualTo(B.class);
}
@Test
@@ -147,13 +139,13 @@ public class GenericTypeResolverTests {
@Test // SPR-11030
public void getGenericsCannotBeResolved() throws Exception {
Class<?>[] resolved = GenericTypeResolver.resolveTypeArguments(List.class, Iterable.class);
assertNull(resolved);
assertThat((Object) resolved).isNull();
}
@Test // SPR-11052
public void getRawMapTypeCannotBeResolved() throws Exception {
Class<?>[] resolved = GenericTypeResolver.resolveTypeArguments(Map.class, Map.class);
assertNull(resolved);
assertThat((Object) resolved).isNull();
}
@Test // SPR-11044
@@ -174,10 +166,10 @@ public class GenericTypeResolverTests {
@Test // SPR-11763
public void resolveIncompleteTypeVariables() {
Class<?>[] resolved = GenericTypeResolver.resolveTypeArguments(IdFixingRepository.class, Repository.class);
assertNotNull(resolved);
assertEquals(2, resolved.length);
assertEquals(Object.class, resolved[0]);
assertEquals(Long.class, resolved[1]);
assertThat(resolved).isNotNull();
assertThat(resolved.length).isEqualTo(2);
assertThat(resolved[0]).isEqualTo(Object.class);
assertThat(resolved[1]).isEqualTo(Long.class);
}

View File

@@ -27,9 +27,7 @@ import org.junit.Test;
import org.springframework.tests.sample.objects.TestObject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Adrian Colyer
@@ -43,43 +41,43 @@ public class LocalVariableTableParameterNameDiscovererTests {
public void methodParameterNameDiscoveryNoArgs() throws NoSuchMethodException {
Method getName = TestObject.class.getMethod("getName");
String[] names = discoverer.getParameterNames(getName);
assertNotNull("should find method info", names);
assertEquals("no argument names", 0, names.length);
assertThat(names).as("should find method info").isNotNull();
assertThat(names.length).as("no argument names").isEqualTo(0);
}
@Test
public void methodParameterNameDiscoveryWithArgs() throws NoSuchMethodException {
Method setName = TestObject.class.getMethod("setName", String.class);
String[] names = discoverer.getParameterNames(setName);
assertNotNull("should find method info", names);
assertEquals("one argument", 1, names.length);
assertEquals("name", names[0]);
assertThat(names).as("should find method info").isNotNull();
assertThat(names.length).as("one argument").isEqualTo(1);
assertThat(names[0]).isEqualTo("name");
}
@Test
public void consParameterNameDiscoveryNoArgs() throws NoSuchMethodException {
Constructor<TestObject> noArgsCons = TestObject.class.getConstructor();
String[] names = discoverer.getParameterNames(noArgsCons);
assertNotNull("should find cons info", names);
assertEquals("no argument names", 0, names.length);
assertThat(names).as("should find cons info").isNotNull();
assertThat(names.length).as("no argument names").isEqualTo(0);
}
@Test
public void consParameterNameDiscoveryArgs() throws NoSuchMethodException {
Constructor<TestObject> twoArgCons = TestObject.class.getConstructor(String.class, int.class);
String[] names = discoverer.getParameterNames(twoArgCons);
assertNotNull("should find cons info", names);
assertEquals("one argument", 2, names.length);
assertEquals("name", names[0]);
assertEquals("age", names[1]);
assertThat(names).as("should find cons info").isNotNull();
assertThat(names.length).as("one argument").isEqualTo(2);
assertThat(names[0]).isEqualTo("name");
assertThat(names[1]).isEqualTo("age");
}
@Test
public void staticMethodParameterNameDiscoveryNoArgs() throws NoSuchMethodException {
Method m = getClass().getMethod("staticMethodNoLocalVars");
String[] names = discoverer.getParameterNames(m);
assertNotNull("should find method info", names);
assertEquals("no argument names", 0, names.length);
assertThat(names).as("should find method info").isNotNull();
assertThat(names.length).as("no argument names").isEqualTo(0);
}
@Test
@@ -88,18 +86,18 @@ public class LocalVariableTableParameterNameDiscovererTests {
Method m1 = clazz.getMethod("staticMethod", Long.TYPE, Long.TYPE);
String[] names = discoverer.getParameterNames(m1);
assertNotNull("should find method info", names);
assertEquals("two arguments", 2, names.length);
assertEquals("x", names[0]);
assertEquals("y", names[1]);
assertThat(names).as("should find method info").isNotNull();
assertThat(names.length).as("two arguments").isEqualTo(2);
assertThat(names[0]).isEqualTo("x");
assertThat(names[1]).isEqualTo("y");
Method m2 = clazz.getMethod("staticMethod", Long.TYPE, Long.TYPE, Long.TYPE);
names = discoverer.getParameterNames(m2);
assertNotNull("should find method info", names);
assertEquals("three arguments", 3, names.length);
assertEquals("x", names[0]);
assertEquals("y", names[1]);
assertEquals("z", names[2]);
assertThat(names).as("should find method info").isNotNull();
assertThat(names.length).as("three arguments").isEqualTo(3);
assertThat(names[0]).isEqualTo("x");
assertThat(names[1]).isEqualTo("y");
assertThat(names[2]).isEqualTo("z");
}
@Test
@@ -108,16 +106,16 @@ public class LocalVariableTableParameterNameDiscovererTests {
Method m1 = clazz.getMethod("staticMethod", Long.TYPE);
String[] names = discoverer.getParameterNames(m1);
assertNotNull("should find method info", names);
assertEquals("one argument", 1, names.length);
assertEquals("x", names[0]);
assertThat(names).as("should find method info").isNotNull();
assertThat(names.length).as("one argument").isEqualTo(1);
assertThat(names[0]).isEqualTo("x");
Method m2 = clazz.getMethod("staticMethod", Long.TYPE, Long.TYPE);
names = discoverer.getParameterNames(m2);
assertNotNull("should find method info", names);
assertEquals("two arguments", 2, names.length);
assertEquals("x", names[0]);
assertEquals("y", names[1]);
assertThat(names).as("should find method info").isNotNull();
assertThat(names.length).as("two arguments").isEqualTo(2);
assertThat(names[0]).isEqualTo("x");
assertThat(names[1]).isEqualTo("y");
}
@Test
@@ -126,18 +124,18 @@ public class LocalVariableTableParameterNameDiscovererTests {
Method m1 = clazz.getMethod("instanceMethod", Double.TYPE, Double.TYPE);
String[] names = discoverer.getParameterNames(m1);
assertNotNull("should find method info", names);
assertEquals("two arguments", 2, names.length);
assertEquals("x", names[0]);
assertEquals("y", names[1]);
assertThat(names).as("should find method info").isNotNull();
assertThat(names.length).as("two arguments").isEqualTo(2);
assertThat(names[0]).isEqualTo("x");
assertThat(names[1]).isEqualTo("y");
Method m2 = clazz.getMethod("instanceMethod", Double.TYPE, Double.TYPE, Double.TYPE);
names = discoverer.getParameterNames(m2);
assertNotNull("should find method info", names);
assertEquals("three arguments", 3, names.length);
assertEquals("x", names[0]);
assertEquals("y", names[1]);
assertEquals("z", names[2]);
assertThat(names).as("should find method info").isNotNull();
assertThat(names.length).as("three arguments").isEqualTo(3);
assertThat(names[0]).isEqualTo("x");
assertThat(names[1]).isEqualTo("y");
assertThat(names[2]).isEqualTo("z");
}
@Test
@@ -146,16 +144,16 @@ public class LocalVariableTableParameterNameDiscovererTests {
Method m1 = clazz.getMethod("instanceMethod", String.class);
String[] names = discoverer.getParameterNames(m1);
assertNotNull("should find method info", names);
assertEquals("one argument", 1, names.length);
assertEquals("aa", names[0]);
assertThat(names).as("should find method info").isNotNull();
assertThat(names.length).as("one argument").isEqualTo(1);
assertThat(names[0]).isEqualTo("aa");
Method m2 = clazz.getMethod("instanceMethod", String.class, String.class);
names = discoverer.getParameterNames(m2);
assertNotNull("should find method info", names);
assertEquals("two arguments", 2, names.length);
assertEquals("aa", names[0]);
assertEquals("bb", names[1]);
assertThat(names).as("should find method info").isNotNull();
assertThat(names.length).as("two arguments").isEqualTo(2);
assertThat(names[0]).isEqualTo("aa");
assertThat(names[1]).isEqualTo("bb");
}
@Test
@@ -164,45 +162,45 @@ public class LocalVariableTableParameterNameDiscovererTests {
Constructor<?> ctor = clazz.getDeclaredConstructor(Object.class);
String[] names = discoverer.getParameterNames(ctor);
assertEquals(1, names.length);
assertEquals("key", names[0]);
assertThat(names.length).isEqualTo(1);
assertThat(names[0]).isEqualTo("key");
ctor = clazz.getDeclaredConstructor(Object.class, Object.class);
names = discoverer.getParameterNames(ctor);
assertEquals(2, names.length);
assertEquals("key", names[0]);
assertEquals("value", names[1]);
assertThat(names.length).isEqualTo(2);
assertThat(names[0]).isEqualTo("key");
assertThat(names[1]).isEqualTo("value");
Method m = clazz.getMethod("generifiedStaticMethod", Object.class);
names = discoverer.getParameterNames(m);
assertEquals(1, names.length);
assertEquals("param", names[0]);
assertThat(names.length).isEqualTo(1);
assertThat(names[0]).isEqualTo("param");
m = clazz.getMethod("generifiedMethod", Object.class, long.class, Object.class, Object.class);
names = discoverer.getParameterNames(m);
assertEquals(4, names.length);
assertEquals("param", names[0]);
assertEquals("x", names[1]);
assertEquals("key", names[2]);
assertEquals("value", names[3]);
assertThat(names.length).isEqualTo(4);
assertThat(names[0]).isEqualTo("param");
assertThat(names[1]).isEqualTo("x");
assertThat(names[2]).isEqualTo("key");
assertThat(names[3]).isEqualTo("value");
m = clazz.getMethod("voidStaticMethod", Object.class, long.class, int.class);
names = discoverer.getParameterNames(m);
assertEquals(3, names.length);
assertEquals("obj", names[0]);
assertEquals("x", names[1]);
assertEquals("i", names[2]);
assertThat(names.length).isEqualTo(3);
assertThat(names[0]).isEqualTo("obj");
assertThat(names[1]).isEqualTo("x");
assertThat(names[2]).isEqualTo("i");
m = clazz.getMethod("nonVoidStaticMethod", Object.class, long.class, int.class);
names = discoverer.getParameterNames(m);
assertEquals(3, names.length);
assertEquals("obj", names[0]);
assertEquals("x", names[1]);
assertEquals("i", names[2]);
assertThat(names.length).isEqualTo(3);
assertThat(names[0]).isEqualTo("obj");
assertThat(names[1]).isEqualTo("x");
assertThat(names[2]).isEqualTo("i");
m = clazz.getMethod("getDate");
names = discoverer.getParameterNames(m);
assertEquals(0, names.length);
assertThat(names.length).isEqualTo(0);
}
@Ignore("Ignored because Ubuntu packages OpenJDK with debug symbols enabled. See SPR-8078.")
@@ -214,15 +212,15 @@ public class LocalVariableTableParameterNameDiscovererTests {
Method m = clazz.getMethod(methodName);
String[] names = discoverer.getParameterNames(m);
assertNull(names);
assertThat(names).isNull();
m = clazz.getMethod(methodName, PrintStream.class);
names = discoverer.getParameterNames(m);
assertNull(names);
assertThat(names).isNull();
m = clazz.getMethod(methodName, PrintStream.class, int.class);
names = discoverer.getParameterNames(m);
assertNull(names);
assertThat(names).isNull();
}

View File

@@ -27,12 +27,8 @@ import java.util.concurrent.Callable;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/**
* @author Arjen Poutsma
@@ -61,48 +57,48 @@ public class MethodParameterTests {
@Test
public void testEquals() throws NoSuchMethodException {
assertEquals(stringParameter, stringParameter);
assertEquals(longParameter, longParameter);
assertEquals(intReturnType, intReturnType);
assertThat(stringParameter).isEqualTo(stringParameter);
assertThat(longParameter).isEqualTo(longParameter);
assertThat(intReturnType).isEqualTo(intReturnType);
assertFalse(stringParameter.equals(longParameter));
assertFalse(stringParameter.equals(intReturnType));
assertFalse(longParameter.equals(stringParameter));
assertFalse(longParameter.equals(intReturnType));
assertFalse(intReturnType.equals(stringParameter));
assertFalse(intReturnType.equals(longParameter));
assertThat(stringParameter.equals(longParameter)).isFalse();
assertThat(stringParameter.equals(intReturnType)).isFalse();
assertThat(longParameter.equals(stringParameter)).isFalse();
assertThat(longParameter.equals(intReturnType)).isFalse();
assertThat(intReturnType.equals(stringParameter)).isFalse();
assertThat(intReturnType.equals(longParameter)).isFalse();
Method method = getClass().getMethod("method", String.class, Long.TYPE);
MethodParameter methodParameter = new MethodParameter(method, 0);
assertEquals(stringParameter, methodParameter);
assertEquals(methodParameter, stringParameter);
assertNotEquals(longParameter, methodParameter);
assertNotEquals(methodParameter, longParameter);
assertThat(methodParameter).isEqualTo(stringParameter);
assertThat(stringParameter).isEqualTo(methodParameter);
assertThat(methodParameter).isNotEqualTo(longParameter);
assertThat(longParameter).isNotEqualTo(methodParameter);
}
@Test
public void testHashCode() throws NoSuchMethodException {
assertEquals(stringParameter.hashCode(), stringParameter.hashCode());
assertEquals(longParameter.hashCode(), longParameter.hashCode());
assertEquals(intReturnType.hashCode(), intReturnType.hashCode());
assertThat(stringParameter.hashCode()).isEqualTo(stringParameter.hashCode());
assertThat(longParameter.hashCode()).isEqualTo(longParameter.hashCode());
assertThat(intReturnType.hashCode()).isEqualTo(intReturnType.hashCode());
Method method = getClass().getMethod("method", String.class, Long.TYPE);
MethodParameter methodParameter = new MethodParameter(method, 0);
assertEquals(stringParameter.hashCode(), methodParameter.hashCode());
assertNotEquals(longParameter.hashCode(), methodParameter.hashCode());
assertThat(methodParameter.hashCode()).isEqualTo(stringParameter.hashCode());
assertThat(methodParameter.hashCode()).isNotEqualTo((long) longParameter.hashCode());
}
@Test
@SuppressWarnings("deprecation")
public void testFactoryMethods() {
assertEquals(stringParameter, MethodParameter.forMethodOrConstructor(method, 0));
assertEquals(longParameter, MethodParameter.forMethodOrConstructor(method, 1));
assertThat(MethodParameter.forMethodOrConstructor(method, 0)).isEqualTo(stringParameter);
assertThat(MethodParameter.forMethodOrConstructor(method, 1)).isEqualTo(longParameter);
assertEquals(stringParameter, MethodParameter.forExecutable(method, 0));
assertEquals(longParameter, MethodParameter.forExecutable(method, 1));
assertThat(MethodParameter.forExecutable(method, 0)).isEqualTo(stringParameter);
assertThat(MethodParameter.forExecutable(method, 1)).isEqualTo(longParameter);
assertEquals(stringParameter, MethodParameter.forParameter(method.getParameters()[0]));
assertEquals(longParameter, MethodParameter.forParameter(method.getParameters()[1]));
assertThat(MethodParameter.forParameter(method.getParameters()[0])).isEqualTo(stringParameter);
assertThat(MethodParameter.forParameter(method.getParameters()[1])).isEqualTo(longParameter);
}
@Test
@@ -115,8 +111,8 @@ public class MethodParameterTests {
public void annotatedConstructorParameterInStaticNestedClass() throws Exception {
Constructor<?> constructor = NestedClass.class.getDeclaredConstructor(String.class);
MethodParameter methodParameter = MethodParameter.forExecutable(constructor, 0);
assertEquals(String.class, methodParameter.getParameterType());
assertNotNull("Failed to find @Param annotation", methodParameter.getParameterAnnotation(Param.class));
assertThat(methodParameter.getParameterType()).isEqualTo(String.class);
assertThat(methodParameter.getParameterAnnotation(Param.class)).as("Failed to find @Param annotation").isNotNull();
}
@Test // SPR-16652
@@ -124,16 +120,16 @@ public class MethodParameterTests {
Constructor<?> constructor = InnerClass.class.getConstructor(getClass(), String.class, Callable.class);
MethodParameter methodParameter = MethodParameter.forExecutable(constructor, 0);
assertEquals(getClass(), methodParameter.getParameterType());
assertNull(methodParameter.getParameterAnnotation(Param.class));
assertThat(methodParameter.getParameterType()).isEqualTo(getClass());
assertThat(methodParameter.getParameterAnnotation(Param.class)).isNull();
methodParameter = MethodParameter.forExecutable(constructor, 1);
assertEquals(String.class, methodParameter.getParameterType());
assertNotNull("Failed to find @Param annotation", methodParameter.getParameterAnnotation(Param.class));
assertThat(methodParameter.getParameterType()).isEqualTo(String.class);
assertThat(methodParameter.getParameterAnnotation(Param.class)).as("Failed to find @Param annotation").isNotNull();
methodParameter = MethodParameter.forExecutable(constructor, 2);
assertEquals(Callable.class, methodParameter.getParameterType());
assertNull(methodParameter.getParameterAnnotation(Param.class));
assertThat(methodParameter.getParameterType()).isEqualTo(Callable.class);
assertThat(methodParameter.getParameterAnnotation(Param.class)).isNull();
}
@Test // SPR-16734
@@ -141,17 +137,16 @@ public class MethodParameterTests {
Constructor<?> constructor = InnerClass.class.getConstructor(getClass(), String.class, Callable.class);
MethodParameter methodParameter = MethodParameter.forExecutable(constructor, 0);
assertEquals(getClass(), methodParameter.getParameterType());
assertEquals(getClass(), methodParameter.getGenericParameterType());
assertThat(methodParameter.getParameterType()).isEqualTo(getClass());
assertThat(methodParameter.getGenericParameterType()).isEqualTo(getClass());
methodParameter = MethodParameter.forExecutable(constructor, 1);
assertEquals(String.class, methodParameter.getParameterType());
assertEquals(String.class, methodParameter.getGenericParameterType());
assertThat(methodParameter.getParameterType()).isEqualTo(String.class);
assertThat(methodParameter.getGenericParameterType()).isEqualTo(String.class);
methodParameter = MethodParameter.forExecutable(constructor, 2);
assertEquals(Callable.class, methodParameter.getParameterType());
assertEquals(ResolvableType.forClassWithGenerics(Callable.class, Integer.class).getType(),
methodParameter.getGenericParameterType());
assertThat(methodParameter.getParameterType()).isEqualTo(Callable.class);
assertThat(methodParameter.getGenericParameterType()).isEqualTo(ResolvableType.forClassWithGenerics(Callable.class, Integer.class).getType());
}

View File

@@ -21,9 +21,7 @@ import java.io.PrintWriter;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rod Johnson
@@ -37,8 +35,8 @@ public class NestedExceptionTests {
String mesg = "mesg of mine";
// Making a class abstract doesn't _really_ prevent instantiation :-)
NestedRuntimeException nex = new NestedRuntimeException(mesg) {};
assertNull(nex.getCause());
assertEquals(nex.getMessage(), mesg);
assertThat(nex.getCause()).isNull();
assertThat(mesg).isEqualTo(nex.getMessage());
// Check printStackTrace
ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -46,7 +44,7 @@ public class NestedExceptionTests {
nex.printStackTrace(pw);
pw.flush();
String stackTrace = new String(baos.toByteArray());
assertTrue(stackTrace.contains(mesg));
assertThat(stackTrace.contains(mesg)).isTrue();
}
@Test
@@ -56,9 +54,9 @@ public class NestedExceptionTests {
Exception rootCause = new Exception(rootCauseMsg);
// Making a class abstract doesn't _really_ prevent instantiation :-)
NestedRuntimeException nex = new NestedRuntimeException(myMessage, rootCause) {};
assertEquals(nex.getCause(), rootCause);
assertTrue(nex.getMessage().contains(myMessage));
assertTrue(nex.getMessage().endsWith(rootCauseMsg));
assertThat(rootCause).isEqualTo(nex.getCause());
assertThat(nex.getMessage().contains(myMessage)).isTrue();
assertThat(nex.getMessage().endsWith(rootCauseMsg)).isTrue();
// check PrintStackTrace
ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -66,8 +64,8 @@ public class NestedExceptionTests {
nex.printStackTrace(pw);
pw.flush();
String stackTrace = new String(baos.toByteArray());
assertTrue(stackTrace.contains(rootCause.getClass().getName()));
assertTrue(stackTrace.contains(rootCauseMsg));
assertThat(stackTrace.contains(rootCause.getClass().getName())).isTrue();
assertThat(stackTrace.contains(rootCauseMsg)).isTrue();
}
@Test
@@ -75,8 +73,8 @@ public class NestedExceptionTests {
String mesg = "mesg of mine";
// Making a class abstract doesn't _really_ prevent instantiation :-)
NestedCheckedException nex = new NestedCheckedException(mesg) {};
assertNull(nex.getCause());
assertEquals(nex.getMessage(), mesg);
assertThat(nex.getCause()).isNull();
assertThat(mesg).isEqualTo(nex.getMessage());
// Check printStackTrace
ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -84,7 +82,7 @@ public class NestedExceptionTests {
nex.printStackTrace(pw);
pw.flush();
String stackTrace = new String(baos.toByteArray());
assertTrue(stackTrace.contains(mesg));
assertThat(stackTrace.contains(mesg)).isTrue();
}
@Test
@@ -94,9 +92,9 @@ public class NestedExceptionTests {
Exception rootCause = new Exception(rootCauseMsg);
// Making a class abstract doesn't _really_ prevent instantiation :-)
NestedCheckedException nex = new NestedCheckedException(myMessage, rootCause) {};
assertEquals(nex.getCause(), rootCause);
assertTrue(nex.getMessage().contains(myMessage));
assertTrue(nex.getMessage().endsWith(rootCauseMsg));
assertThat(rootCause).isEqualTo(nex.getCause());
assertThat(nex.getMessage().contains(myMessage)).isTrue();
assertThat(nex.getMessage().endsWith(rootCauseMsg)).isTrue();
// check PrintStackTrace
ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -104,8 +102,8 @@ public class NestedExceptionTests {
nex.printStackTrace(pw);
pw.flush();
String stackTrace = new String(baos.toByteArray());
assertTrue(stackTrace.contains(rootCause.getClass().getName()));
assertTrue(stackTrace.contains(rootCauseMsg));
assertThat(stackTrace.contains(rootCause.getClass().getName())).isTrue();
assertThat(stackTrace.contains(rootCauseMsg)).isTrue();
}
}

View File

@@ -20,7 +20,7 @@ import java.util.Comparator;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for the {@link OrderComparator} class.
@@ -36,65 +36,65 @@ public class OrderComparatorTests {
@Test
public void compareOrderedInstancesBefore() {
assertEquals(-1, this.comparator.compare(new StubOrdered(100), new StubOrdered(2000)));
assertThat(this.comparator.compare(new StubOrdered(100), new StubOrdered(2000))).isEqualTo(-1);
}
@Test
public void compareOrderedInstancesSame() {
assertEquals(0, this.comparator.compare(new StubOrdered(100), new StubOrdered(100)));
assertThat(this.comparator.compare(new StubOrdered(100), new StubOrdered(100))).isEqualTo(0);
}
@Test
public void compareOrderedInstancesAfter() {
assertEquals(1, this.comparator.compare(new StubOrdered(982300), new StubOrdered(100)));
assertThat(this.comparator.compare(new StubOrdered(982300), new StubOrdered(100))).isEqualTo(1);
}
@Test
public void compareOrderedInstancesNullFirst() {
assertEquals(1, this.comparator.compare(null, new StubOrdered(100)));
assertThat(this.comparator.compare(null, new StubOrdered(100))).isEqualTo(1);
}
@Test
public void compareOrderedInstancesNullLast() {
assertEquals(-1, this.comparator.compare(new StubOrdered(100), null));
assertThat(this.comparator.compare(new StubOrdered(100), null)).isEqualTo(-1);
}
@Test
public void compareOrderedInstancesDoubleNull() {
assertEquals(0, this.comparator.compare(null, null));
assertThat(this.comparator.compare(null, null)).isEqualTo(0);
}
@Test
public void compareTwoNonOrderedInstancesEndsUpAsSame() {
assertEquals(0, this.comparator.compare(new Object(), new Object()));
assertThat(this.comparator.compare(new Object(), new Object())).isEqualTo(0);
}
@Test
public void compareWithSimpleSourceProvider() {
Comparator<Object> customComparator = this.comparator.withSourceProvider(
new TestSourceProvider(5L, new StubOrdered(25)));
assertEquals(-1, customComparator.compare(new StubOrdered(10), 5L));
assertThat(customComparator.compare(new StubOrdered(10), 5L)).isEqualTo(-1);
}
@Test
public void compareWithSourceProviderArray() {
Comparator<Object> customComparator = this.comparator.withSourceProvider(
new TestSourceProvider(5L, new Object[] {new StubOrdered(10), new StubOrdered(-25)}));
assertEquals(-1, customComparator.compare(5L, new Object()));
assertThat(customComparator.compare(5L, new Object())).isEqualTo(-1);
}
@Test
public void compareWithSourceProviderArrayNoMatch() {
Comparator<Object> customComparator = this.comparator.withSourceProvider(
new TestSourceProvider(5L, new Object[]{new Object(), new Object()}));
assertEquals(0, customComparator.compare(new Object(), 5L));
assertThat(customComparator.compare(new Object(), 5L)).isEqualTo(0);
}
@Test
public void compareWithSourceProviderEmpty() {
Comparator<Object> customComparator = this.comparator.withSourceProvider(
new TestSourceProvider(50L, new Object()));
assertEquals(0, customComparator.compare(new Object(), 5L));
assertThat(customComparator.compare(new Object(), 5L)).isEqualTo(0);
}

View File

@@ -22,7 +22,7 @@ import java.util.Map;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test fixture for {@link ParameterizedTypeReference}.
@@ -35,35 +35,35 @@ public class ParameterizedTypeReferenceTests {
@Test
public void stringTypeReference() {
ParameterizedTypeReference<String> typeReference = new ParameterizedTypeReference<String>() {};
assertEquals(String.class, typeReference.getType());
assertThat(typeReference.getType()).isEqualTo(String.class);
}
@Test
public void mapTypeReference() throws Exception {
Type mapType = getClass().getMethod("mapMethod").getGenericReturnType();
ParameterizedTypeReference<Map<Object,String>> typeReference = new ParameterizedTypeReference<Map<Object,String>>() {};
assertEquals(mapType, typeReference.getType());
assertThat(typeReference.getType()).isEqualTo(mapType);
}
@Test
public void listTypeReference() throws Exception {
Type listType = getClass().getMethod("listMethod").getGenericReturnType();
ParameterizedTypeReference<List<String>> typeReference = new ParameterizedTypeReference<List<String>>() {};
assertEquals(listType, typeReference.getType());
assertThat(typeReference.getType()).isEqualTo(listType);
}
@Test
public void reflectiveTypeReferenceWithSpecificDeclaration() throws Exception{
Type listType = getClass().getMethod("listMethod").getGenericReturnType();
ParameterizedTypeReference<List<String>> typeReference = ParameterizedTypeReference.forType(listType);
assertEquals(listType, typeReference.getType());
assertThat(typeReference.getType()).isEqualTo(listType);
}
@Test
public void reflectiveTypeReferenceWithGenericDeclaration() throws Exception{
Type listType = getClass().getMethod("listMethod").getGenericReturnType();
ParameterizedTypeReference<?> typeReference = ParameterizedTypeReference.forType(listType);
assertEquals(listType, typeReference.getType());
assertThat(typeReference.getType()).isEqualTo(listType);
}

View File

@@ -24,8 +24,7 @@ import org.junit.Test;
import org.springframework.tests.sample.objects.TestObject;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
public class PrioritizedParameterNameDiscovererTests {
@@ -64,30 +63,30 @@ public class PrioritizedParameterNameDiscovererTests {
@Test
public void noParametersDiscoverers() {
ParameterNameDiscoverer pnd = new PrioritizedParameterNameDiscoverer();
assertNull(pnd.getParameterNames(anyMethod));
assertNull(pnd.getParameterNames((Constructor<?>) null));
assertThat(pnd.getParameterNames(anyMethod)).isNull();
assertThat(pnd.getParameterNames((Constructor<?>) null)).isNull();
}
@Test
public void orderedParameterDiscoverers1() {
PrioritizedParameterNameDiscoverer pnd = new PrioritizedParameterNameDiscoverer();
pnd.addDiscoverer(returnsFooBar);
assertTrue(Arrays.equals(FOO_BAR, pnd.getParameterNames(anyMethod)));
assertTrue(Arrays.equals(FOO_BAR, pnd.getParameterNames((Constructor<?>) null)));
assertThat(Arrays.equals(FOO_BAR, pnd.getParameterNames(anyMethod))).isTrue();
assertThat(Arrays.equals(FOO_BAR, pnd.getParameterNames((Constructor<?>) null))).isTrue();
pnd.addDiscoverer(returnsSomethingElse);
assertTrue(Arrays.equals(FOO_BAR, pnd.getParameterNames(anyMethod)));
assertTrue(Arrays.equals(FOO_BAR, pnd.getParameterNames((Constructor<?>) null)));
assertThat(Arrays.equals(FOO_BAR, pnd.getParameterNames(anyMethod))).isTrue();
assertThat(Arrays.equals(FOO_BAR, pnd.getParameterNames((Constructor<?>) null))).isTrue();
}
@Test
public void orderedParameterDiscoverers2() {
PrioritizedParameterNameDiscoverer pnd = new PrioritizedParameterNameDiscoverer();
pnd.addDiscoverer(returnsSomethingElse);
assertTrue(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames(anyMethod)));
assertTrue(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames((Constructor<?>) null)));
assertThat(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames(anyMethod))).isTrue();
assertThat(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames((Constructor<?>) null))).isTrue();
pnd.addDiscoverer(returnsFooBar);
assertTrue(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames(anyMethod)));
assertTrue(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames((Constructor<?>) null)));
assertThat(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames(anyMethod))).isTrue();
assertThat(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames((Constructor<?>) null))).isTrue();
}
}

View File

@@ -33,12 +33,7 @@ import rx.Completable;
import rx.Observable;
import rx.Single;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link ReactiveAdapterRegistry}.
@@ -54,29 +49,29 @@ public class ReactiveAdapterRegistryTests {
public void defaultAdapterRegistrations() {
// Reactor
assertNotNull(getAdapter(Mono.class));
assertNotNull(getAdapter(Flux.class));
assertThat(getAdapter(Mono.class)).isNotNull();
assertThat(getAdapter(Flux.class)).isNotNull();
// Publisher
assertNotNull(getAdapter(Publisher.class));
assertThat(getAdapter(Publisher.class)).isNotNull();
// Completable
assertNotNull(getAdapter(CompletableFuture.class));
assertThat(getAdapter(CompletableFuture.class)).isNotNull();
// RxJava 1
assertNotNull(getAdapter(Observable.class));
assertNotNull(getAdapter(Single.class));
assertNotNull(getAdapter(Completable.class));
assertThat(getAdapter(Observable.class)).isNotNull();
assertThat(getAdapter(Single.class)).isNotNull();
assertThat(getAdapter(Completable.class)).isNotNull();
// RxJava 2
assertNotNull(getAdapter(Flowable.class));
assertNotNull(getAdapter(io.reactivex.Observable.class));
assertNotNull(getAdapter(io.reactivex.Single.class));
assertNotNull(getAdapter(Maybe.class));
assertNotNull(getAdapter(io.reactivex.Completable.class));
assertThat(getAdapter(Flowable.class)).isNotNull();
assertThat(getAdapter(io.reactivex.Observable.class)).isNotNull();
assertThat(getAdapter(io.reactivex.Single.class)).isNotNull();
assertThat(getAdapter(Maybe.class)).isNotNull();
assertThat(getAdapter(io.reactivex.Completable.class)).isNotNull();
// Coroutines
assertNotNull(getAdapter(Deferred.class));
assertThat(getAdapter(Deferred.class)).isNotNull();
}
@Test
@@ -85,7 +80,7 @@ public class ReactiveAdapterRegistryTests {
ReactiveAdapter adapter1 = getAdapter(Flux.class);
ReactiveAdapter adapter2 = getAdapter(FluxProcessor.class);
assertSame(adapter1, adapter2);
assertThat(adapter2).isSameAs(adapter1);
this.registry.registerReactiveType(
ReactiveTypeDescriptor.multiValue(FluxProcessor.class, FluxProcessor::empty),
@@ -94,8 +89,8 @@ public class ReactiveAdapterRegistryTests {
ReactiveAdapter adapter3 = getAdapter(FluxProcessor.class);
assertNotNull(adapter3);
assertNotSame(adapter1, adapter3);
assertThat(adapter3).isNotNull();
assertThat(adapter3).isNotSameAs(adapter1);
}
@Test
@@ -103,8 +98,9 @@ public class ReactiveAdapterRegistryTests {
List<Integer> sequence = Arrays.asList(1, 2, 3);
Publisher<Integer> source = Flowable.fromIterable(sequence);
Object target = getAdapter(Flux.class).fromPublisher(source);
assertTrue(target instanceof Flux);
assertEquals(sequence, ((Flux<Integer>) target).collectList().block(Duration.ofMillis(1000)));
boolean condition = target instanceof Flux;
assertThat(condition).isTrue();
assertThat(((Flux<Integer>) target).collectList().block(Duration.ofMillis(1000))).isEqualTo(sequence);
}
// TODO: publisherToMono/CompletableFuture vs Single (ISE on multiple elements)?
@@ -113,16 +109,18 @@ public class ReactiveAdapterRegistryTests {
public void publisherToMono() {
Publisher<Integer> source = Flowable.fromArray(1, 2, 3);
Object target = getAdapter(Mono.class).fromPublisher(source);
assertTrue(target instanceof Mono);
assertEquals(Integer.valueOf(1), ((Mono<Integer>) target).block(Duration.ofMillis(1000)));
boolean condition = target instanceof Mono;
assertThat(condition).isTrue();
assertThat(((Mono<Integer>) target).block(Duration.ofMillis(1000))).isEqualTo(Integer.valueOf(1));
}
@Test
public void publisherToCompletableFuture() throws Exception {
Publisher<Integer> source = Flowable.fromArray(1, 2, 3);
Object target = getAdapter(CompletableFuture.class).fromPublisher(source);
assertTrue(target instanceof CompletableFuture);
assertEquals(Integer.valueOf(1), ((CompletableFuture<Integer>) target).get());
boolean condition = target instanceof CompletableFuture;
assertThat(condition).isTrue();
assertThat(((CompletableFuture<Integer>) target).get()).isEqualTo(Integer.valueOf(1));
}
@Test
@@ -130,24 +128,27 @@ public class ReactiveAdapterRegistryTests {
List<Integer> sequence = Arrays.asList(1, 2, 3);
Publisher<Integer> source = Flowable.fromIterable(sequence);
Object target = getAdapter(rx.Observable.class).fromPublisher(source);
assertTrue(target instanceof rx.Observable);
assertEquals(sequence, ((rx.Observable<?>) target).toList().toBlocking().first());
boolean condition = target instanceof Observable;
assertThat(condition).isTrue();
assertThat(((Observable<?>) target).toList().toBlocking().first()).isEqualTo(sequence);
}
@Test
public void publisherToRxSingle() {
Publisher<Integer> source = Flowable.fromArray(1);
Object target = getAdapter(rx.Single.class).fromPublisher(source);
assertTrue(target instanceof rx.Single);
assertEquals(Integer.valueOf(1), ((rx.Single<Integer>) target).toBlocking().value());
boolean condition = target instanceof Single;
assertThat(condition).isTrue();
assertThat(((Single<Integer>) target).toBlocking().value()).isEqualTo(Integer.valueOf(1));
}
@Test
public void publisherToRxCompletable() {
Publisher<Integer> source = Flowable.fromArray(1, 2, 3);
Object target = getAdapter(rx.Completable.class).fromPublisher(source);
assertTrue(target instanceof rx.Completable);
assertNull(((rx.Completable) target).get());
boolean condition = target instanceof Completable;
assertThat(condition).isTrue();
assertThat(((Completable) target).get()).isNull();
}
@Test
@@ -155,8 +156,9 @@ public class ReactiveAdapterRegistryTests {
List<Integer> sequence = Arrays.asList(1, 2, 3);
Publisher<Integer> source = Flux.fromIterable(sequence);
Object target = getAdapter(io.reactivex.Flowable.class).fromPublisher(source);
assertTrue(target instanceof io.reactivex.Flowable);
assertEquals(sequence, ((io.reactivex.Flowable<?>) target).toList().blockingGet());
boolean condition = target instanceof Flowable;
assertThat(condition).isTrue();
assertThat(((Flowable<?>) target).toList().blockingGet()).isEqualTo(sequence);
}
@Test
@@ -164,24 +166,27 @@ public class ReactiveAdapterRegistryTests {
List<Integer> sequence = Arrays.asList(1, 2, 3);
Publisher<Integer> source = Flowable.fromIterable(sequence);
Object target = getAdapter(io.reactivex.Observable.class).fromPublisher(source);
assertTrue(target instanceof io.reactivex.Observable);
assertEquals(sequence, ((io.reactivex.Observable<?>) target).toList().blockingGet());
boolean condition = target instanceof io.reactivex.Observable;
assertThat(condition).isTrue();
assertThat(((io.reactivex.Observable<?>) target).toList().blockingGet()).isEqualTo(sequence);
}
@Test
public void publisherToReactivexSingle() {
Publisher<Integer> source = Flowable.fromArray(1);
Object target = getAdapter(io.reactivex.Single.class).fromPublisher(source);
assertTrue(target instanceof io.reactivex.Single);
assertEquals(Integer.valueOf(1), ((io.reactivex.Single<Integer>) target).blockingGet());
boolean condition = target instanceof io.reactivex.Single;
assertThat(condition).isTrue();
assertThat(((io.reactivex.Single<Integer>) target).blockingGet()).isEqualTo(Integer.valueOf(1));
}
@Test
public void publisherToReactivexCompletable() {
Publisher<Integer> source = Flowable.fromArray(1, 2, 3);
Object target = getAdapter(io.reactivex.Completable.class).fromPublisher(source);
assertTrue(target instanceof io.reactivex.Completable);
assertNull(((io.reactivex.Completable) target).blockingGet());
boolean condition = target instanceof io.reactivex.Completable;
assertThat(condition).isTrue();
assertThat(((io.reactivex.Completable) target).blockingGet()).isNull();
}
@Test
@@ -189,23 +194,26 @@ public class ReactiveAdapterRegistryTests {
List<Integer> sequence = Arrays.asList(1, 2, 3);
Object source = rx.Observable.from(sequence);
Object target = getAdapter(rx.Observable.class).toPublisher(source);
assertTrue("Expected Flux Publisher: " + target.getClass().getName(), target instanceof Flux);
assertEquals(sequence, ((Flux<Integer>) target).collectList().block(Duration.ofMillis(1000)));
boolean condition = target instanceof Flux;
assertThat(condition).as("Expected Flux Publisher: " + target.getClass().getName()).isTrue();
assertThat(((Flux<Integer>) target).collectList().block(Duration.ofMillis(1000))).isEqualTo(sequence);
}
@Test
public void rxSingleToPublisher() {
Object source = rx.Single.just(1);
Object target = getAdapter(rx.Single.class).toPublisher(source);
assertTrue("Expected Mono Publisher: " + target.getClass().getName(), target instanceof Mono);
assertEquals(Integer.valueOf(1), ((Mono<Integer>) target).block(Duration.ofMillis(1000)));
boolean condition = target instanceof Mono;
assertThat(condition).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue();
assertThat(((Mono<Integer>) target).block(Duration.ofMillis(1000))).isEqualTo(Integer.valueOf(1));
}
@Test
public void rxCompletableToPublisher() {
Object source = rx.Completable.complete();
Object target = getAdapter(rx.Completable.class).toPublisher(source);
assertTrue("Expected Mono Publisher: " + target.getClass().getName(), target instanceof Mono);
boolean condition = target instanceof Mono;
assertThat(condition).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue();
((Mono<Void>) target).block(Duration.ofMillis(1000));
}
@@ -214,8 +222,9 @@ public class ReactiveAdapterRegistryTests {
List<Integer> sequence = Arrays.asList(1, 2, 3);
Object source = io.reactivex.Flowable.fromIterable(sequence);
Object target = getAdapter(io.reactivex.Flowable.class).toPublisher(source);
assertTrue("Expected Flux Publisher: " + target.getClass().getName(), target instanceof Flux);
assertEquals(sequence, ((Flux<Integer>) target).collectList().block(Duration.ofMillis(1000)));
boolean condition = target instanceof Flux;
assertThat(condition).as("Expected Flux Publisher: " + target.getClass().getName()).isTrue();
assertThat(((Flux<Integer>) target).collectList().block(Duration.ofMillis(1000))).isEqualTo(sequence);
}
@Test
@@ -223,23 +232,26 @@ public class ReactiveAdapterRegistryTests {
List<Integer> sequence = Arrays.asList(1, 2, 3);
Object source = io.reactivex.Observable.fromIterable(sequence);
Object target = getAdapter(io.reactivex.Observable.class).toPublisher(source);
assertTrue("Expected Flux Publisher: " + target.getClass().getName(), target instanceof Flux);
assertEquals(sequence, ((Flux<Integer>) target).collectList().block(Duration.ofMillis(1000)));
boolean condition = target instanceof Flux;
assertThat(condition).as("Expected Flux Publisher: " + target.getClass().getName()).isTrue();
assertThat(((Flux<Integer>) target).collectList().block(Duration.ofMillis(1000))).isEqualTo(sequence);
}
@Test
public void reactivexSingleToPublisher() {
Object source = io.reactivex.Single.just(1);
Object target = getAdapter(io.reactivex.Single.class).toPublisher(source);
assertTrue("Expected Mono Publisher: " + target.getClass().getName(), target instanceof Mono);
assertEquals(Integer.valueOf(1), ((Mono<Integer>) target).block(Duration.ofMillis(1000)));
boolean condition = target instanceof Mono;
assertThat(condition).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue();
assertThat(((Mono<Integer>) target).block(Duration.ofMillis(1000))).isEqualTo(Integer.valueOf(1));
}
@Test
public void reactivexCompletableToPublisher() {
Object source = io.reactivex.Completable.complete();
Object target = getAdapter(io.reactivex.Completable.class).toPublisher(source);
assertTrue("Expected Mono Publisher: " + target.getClass().getName(), target instanceof Mono);
boolean condition = target instanceof Mono;
assertThat(condition).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue();
((Mono<Void>) target).block(Duration.ofMillis(1000));
}
@@ -248,8 +260,9 @@ public class ReactiveAdapterRegistryTests {
CompletableFuture<Integer> future = new CompletableFuture<>();
future.complete(1);
Object target = getAdapter(CompletableFuture.class).toPublisher(future);
assertTrue("Expected Mono Publisher: " + target.getClass().getName(), target instanceof Mono);
assertEquals(Integer.valueOf(1), ((Mono<Integer>) target).block(Duration.ofMillis(1000)));
boolean condition = target instanceof Mono;
assertThat(condition).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue();
assertThat(((Mono<Integer>) target).block(Duration.ofMillis(1000))).isEqualTo(Integer.valueOf(1));
}

View File

@@ -54,9 +54,6 @@ import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
@@ -106,8 +103,8 @@ public class ResolvableTypeTests {
ResolvableType type = ResolvableType.forClass(ExtendsList.class);
assertThat(type.getType()).isEqualTo(ExtendsList.class);
assertThat(type.getRawClass()).isEqualTo(ExtendsList.class);
assertTrue(type.isAssignableFrom(ExtendsList.class));
assertFalse(type.isAssignableFrom(ArrayList.class));
assertThat(type.isAssignableFrom(ExtendsList.class)).isTrue();
assertThat(type.isAssignableFrom(ArrayList.class)).isFalse();
}
@Test
@@ -115,8 +112,8 @@ public class ResolvableTypeTests {
ResolvableType type = ResolvableType.forClass(null);
assertThat(type.getType()).isEqualTo(Object.class);
assertThat(type.getRawClass()).isEqualTo(Object.class);
assertTrue(type.isAssignableFrom(Object.class));
assertTrue(type.isAssignableFrom(String.class));
assertThat(type.isAssignableFrom(Object.class)).isTrue();
assertThat(type.isAssignableFrom(String.class)).isTrue();
}
@Test
@@ -124,8 +121,8 @@ public class ResolvableTypeTests {
ResolvableType type = ResolvableType.forRawClass(ExtendsList.class);
assertThat(type.getType()).isEqualTo(ExtendsList.class);
assertThat(type.getRawClass()).isEqualTo(ExtendsList.class);
assertTrue(type.isAssignableFrom(ExtendsList.class));
assertFalse(type.isAssignableFrom(ArrayList.class));
assertThat(type.isAssignableFrom(ExtendsList.class)).isTrue();
assertThat(type.isAssignableFrom(ArrayList.class)).isFalse();
}
@Test
@@ -133,8 +130,8 @@ public class ResolvableTypeTests {
ResolvableType type = ResolvableType.forRawClass(null);
assertThat(type.getType()).isEqualTo(Object.class);
assertThat(type.getRawClass()).isEqualTo(Object.class);
assertTrue(type.isAssignableFrom(Object.class));
assertTrue(type.isAssignableFrom(String.class));
assertThat(type.isAssignableFrom(Object.class)).isTrue();
assertThat(type.isAssignableFrom(String.class)).isTrue();
}
@Test
@@ -186,8 +183,8 @@ public class ResolvableTypeTests {
assertThat(type2.resolve()).isEqualTo(List.class);
assertThat(type2.getSource()).isSameAs(field2);
assertEquals(type, type2);
assertEquals(type.hashCode(), type2.hashCode());
assertThat(type2).isEqualTo(type);
assertThat(type2.hashCode()).isEqualTo(type.hashCode());
}
@Test
@@ -899,7 +896,7 @@ public class ResolvableTypeTests {
Type sourceType = Methods.class.getMethod("charSequenceReturn").getGenericReturnType();
ResolvableType reflectiveType = ResolvableType.forType(sourceType);
ResolvableType declaredType = ResolvableType.forType(new ParameterizedTypeReference<List<CharSequence>>() {});
assertEquals(reflectiveType, declaredType);
assertThat(declaredType).isEqualTo(reflectiveType);
}
@Test
@@ -985,19 +982,19 @@ public class ResolvableTypeTests {
assertThatResolvableType(charSequenceType).isAssignableFrom(charSequenceType, stringType).isNotAssignableFrom(objectType);
assertThatResolvableType(stringType).isAssignableFrom(stringType).isNotAssignableFrom(objectType, charSequenceType);
assertTrue(objectType.isAssignableFrom(String.class));
assertTrue(objectType.isAssignableFrom(StringBuilder.class));
assertTrue(charSequenceType.isAssignableFrom(String.class));
assertTrue(charSequenceType.isAssignableFrom(StringBuilder.class));
assertTrue(stringType.isAssignableFrom(String.class));
assertFalse(stringType.isAssignableFrom(StringBuilder.class));
assertThat(objectType.isAssignableFrom(String.class)).isTrue();
assertThat(objectType.isAssignableFrom(StringBuilder.class)).isTrue();
assertThat(charSequenceType.isAssignableFrom(String.class)).isTrue();
assertThat(charSequenceType.isAssignableFrom(StringBuilder.class)).isTrue();
assertThat(stringType.isAssignableFrom(String.class)).isTrue();
assertThat(stringType.isAssignableFrom(StringBuilder.class)).isFalse();
assertTrue(objectType.isInstance("a String"));
assertTrue(objectType.isInstance(new StringBuilder("a StringBuilder")));
assertTrue(charSequenceType.isInstance("a String"));
assertTrue(charSequenceType.isInstance(new StringBuilder("a StringBuilder")));
assertTrue(stringType.isInstance("a String"));
assertFalse(stringType.isInstance(new StringBuilder("a StringBuilder")));
assertThat(objectType.isInstance("a String")).isTrue();
assertThat(objectType.isInstance(new StringBuilder("a StringBuilder"))).isTrue();
assertThat(charSequenceType.isInstance("a String")).isTrue();
assertThat(charSequenceType.isInstance(new StringBuilder("a StringBuilder"))).isTrue();
assertThat(stringType.isInstance("a String")).isTrue();
assertThat(stringType.isInstance(new StringBuilder("a StringBuilder"))).isFalse();
}
@Test
@@ -1282,8 +1279,8 @@ public class ResolvableTypeTests {
@Test
public void testSpr11219() throws Exception {
ResolvableType type = ResolvableType.forField(BaseProvider.class.getField("stuff"), BaseProvider.class);
assertTrue(type.getNested(2).isAssignableFrom(ResolvableType.forClass(BaseImplementation.class)));
assertEquals("java.util.Collection<org.springframework.core.ResolvableTypeTests$IBase<?>>", type.toString());
assertThat(type.getNested(2).isAssignableFrom(ResolvableType.forClass(BaseImplementation.class))).isTrue();
assertThat(type.toString()).isEqualTo("java.util.Collection<org.springframework.core.ResolvableTypeTests$IBase<?>>");
}
@Test
@@ -1301,8 +1298,8 @@ public class ResolvableTypeTests {
ResolvableType collectionClass = ResolvableType.forRawClass(Collection.class);
ResolvableType setClass = ResolvableType.forRawClass(Set.class);
ResolvableType fromReturnType = ResolvableType.forMethodReturnType(Methods.class.getMethod("wildcardSet"));
assertTrue(collectionClass.isAssignableFrom(fromReturnType));
assertTrue(setClass.isAssignableFrom(fromReturnType));
assertThat(collectionClass.isAssignableFrom(fromReturnType)).isTrue();
assertThat(setClass.isAssignableFrom(fromReturnType)).isTrue();
}
@Test

View File

@@ -18,8 +18,7 @@ package org.springframework.core;
import org.junit.Test;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Juergen Hoeller
@@ -33,12 +32,12 @@ public class SimpleAliasRegistryTests {
registry.registerAlias("testAlias", "testAlias2");
registry.registerAlias("testAlias2", "testAlias3");
assertTrue(registry.hasAlias("test", "testAlias"));
assertTrue(registry.hasAlias("test", "testAlias2"));
assertTrue(registry.hasAlias("test", "testAlias3"));
assertSame("test", registry.canonicalName("testAlias"));
assertSame("test", registry.canonicalName("testAlias2"));
assertSame("test", registry.canonicalName("testAlias3"));
assertThat(registry.hasAlias("test", "testAlias")).isTrue();
assertThat(registry.hasAlias("test", "testAlias2")).isTrue();
assertThat(registry.hasAlias("test", "testAlias3")).isTrue();
assertThat(registry.canonicalName("testAlias")).isSameAs("test");
assertThat(registry.canonicalName("testAlias2")).isSameAs("test");
assertThat(registry.canonicalName("testAlias3")).isSameAs("test");
}
@Test // SPR-17191
@@ -46,19 +45,19 @@ public class SimpleAliasRegistryTests {
SimpleAliasRegistry registry = new SimpleAliasRegistry();
registry.registerAlias("name", "alias_a");
registry.registerAlias("name", "alias_b");
assertTrue(registry.hasAlias("name", "alias_a"));
assertTrue(registry.hasAlias("name", "alias_b"));
assertThat(registry.hasAlias("name", "alias_a")).isTrue();
assertThat(registry.hasAlias("name", "alias_b")).isTrue();
registry.registerAlias("real_name", "name");
assertTrue(registry.hasAlias("real_name", "name"));
assertTrue(registry.hasAlias("real_name", "alias_a"));
assertTrue(registry.hasAlias("real_name", "alias_b"));
assertThat(registry.hasAlias("real_name", "name")).isTrue();
assertThat(registry.hasAlias("real_name", "alias_a")).isTrue();
assertThat(registry.hasAlias("real_name", "alias_b")).isTrue();
registry.registerAlias("name", "alias_c");
assertTrue(registry.hasAlias("real_name", "name"));
assertTrue(registry.hasAlias("real_name", "alias_a"));
assertTrue(registry.hasAlias("real_name", "alias_b"));
assertTrue(registry.hasAlias("real_name", "alias_c"));
assertThat(registry.hasAlias("real_name", "name")).isTrue();
assertThat(registry.hasAlias("real_name", "alias_a")).isTrue();
assertThat(registry.hasAlias("real_name", "alias_b")).isTrue();
assertThat(registry.hasAlias("real_name", "alias_c")).isTrue();
}
}

View File

@@ -54,12 +54,6 @@ import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.core.annotation.AnnotatedElementUtils.findAllMergedAnnotations;
import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation;
import static org.springframework.core.annotation.AnnotatedElementUtils.getAllAnnotationAttributes;
@@ -90,26 +84,26 @@ public class AnnotatedElementUtilsTests {
@Test
public void getMetaAnnotationTypesOnNonAnnotatedClass() {
assertTrue(getMetaAnnotationTypes(NonAnnotatedClass.class, TransactionalComponent.class).isEmpty());
assertTrue(getMetaAnnotationTypes(NonAnnotatedClass.class, TransactionalComponent.class.getName()).isEmpty());
assertThat(getMetaAnnotationTypes(NonAnnotatedClass.class, TransactionalComponent.class).isEmpty()).isTrue();
assertThat(getMetaAnnotationTypes(NonAnnotatedClass.class, TransactionalComponent.class.getName()).isEmpty()).isTrue();
}
@Test
public void getMetaAnnotationTypesOnClassWithMetaDepth1() {
Set<String> names = getMetaAnnotationTypes(TransactionalComponentClass.class, TransactionalComponent.class);
assertEquals(names(Transactional.class, Component.class, Indexed.class), names);
assertThat(names).isEqualTo(names(Transactional.class, Component.class, Indexed.class));
names = getMetaAnnotationTypes(TransactionalComponentClass.class, TransactionalComponent.class.getName());
assertEquals(names(Transactional.class, Component.class, Indexed.class), names);
assertThat(names).isEqualTo(names(Transactional.class, Component.class, Indexed.class));
}
@Test
public void getMetaAnnotationTypesOnClassWithMetaDepth2() {
Set<String> names = getMetaAnnotationTypes(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class);
assertEquals(names(TransactionalComponent.class, Transactional.class, Component.class, Indexed.class), names);
assertThat(names).isEqualTo(names(TransactionalComponent.class, Transactional.class, Component.class, Indexed.class));
names = getMetaAnnotationTypes(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class.getName());
assertEquals(names(TransactionalComponent.class, Transactional.class, Component.class, Indexed.class), names);
assertThat(names).isEqualTo(names(TransactionalComponent.class, Transactional.class, Component.class, Indexed.class));
}
private Set<String> names(Class<?>... classes) {
@@ -118,124 +112,122 @@ public class AnnotatedElementUtilsTests {
@Test
public void hasMetaAnnotationTypesOnNonAnnotatedClass() {
assertFalse(hasMetaAnnotationTypes(NonAnnotatedClass.class, TX_NAME));
assertThat(hasMetaAnnotationTypes(NonAnnotatedClass.class, TX_NAME)).isFalse();
}
@Test
public void hasMetaAnnotationTypesOnClassWithMetaDepth0() {
assertFalse(hasMetaAnnotationTypes(TransactionalComponentClass.class, TransactionalComponent.class.getName()));
assertThat(hasMetaAnnotationTypes(TransactionalComponentClass.class, TransactionalComponent.class.getName())).isFalse();
}
@Test
public void hasMetaAnnotationTypesOnClassWithMetaDepth1() {
assertTrue(hasMetaAnnotationTypes(TransactionalComponentClass.class, TX_NAME));
assertTrue(hasMetaAnnotationTypes(TransactionalComponentClass.class, Component.class.getName()));
assertThat(hasMetaAnnotationTypes(TransactionalComponentClass.class, TX_NAME)).isTrue();
assertThat(hasMetaAnnotationTypes(TransactionalComponentClass.class, Component.class.getName())).isTrue();
}
@Test
public void hasMetaAnnotationTypesOnClassWithMetaDepth2() {
assertTrue(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, TX_NAME));
assertTrue(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, Component.class.getName()));
assertFalse(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class.getName()));
assertThat(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, TX_NAME)).isTrue();
assertThat(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, Component.class.getName())).isTrue();
assertThat(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class.getName())).isFalse();
}
@Test
public void isAnnotatedOnNonAnnotatedClass() {
assertFalse(isAnnotated(NonAnnotatedClass.class, Transactional.class));
assertThat(isAnnotated(NonAnnotatedClass.class, Transactional.class)).isFalse();
}
@Test
public void isAnnotatedOnClassWithMetaDepth() {
assertTrue(isAnnotated(TransactionalComponentClass.class, TransactionalComponent.class));
assertFalse("isAnnotated() does not search the class hierarchy.",
isAnnotated(SubTransactionalComponentClass.class, TransactionalComponent.class));
assertTrue(isAnnotated(TransactionalComponentClass.class, Transactional.class));
assertTrue(isAnnotated(TransactionalComponentClass.class, Component.class));
assertTrue(isAnnotated(ComposedTransactionalComponentClass.class, Transactional.class));
assertTrue(isAnnotated(ComposedTransactionalComponentClass.class, Component.class));
assertTrue(isAnnotated(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class));
assertThat(isAnnotated(TransactionalComponentClass.class, TransactionalComponent.class)).isTrue();
assertThat(isAnnotated(SubTransactionalComponentClass.class, TransactionalComponent.class)).as("isAnnotated() does not search the class hierarchy.").isFalse();
assertThat(isAnnotated(TransactionalComponentClass.class, Transactional.class)).isTrue();
assertThat(isAnnotated(TransactionalComponentClass.class, Component.class)).isTrue();
assertThat(isAnnotated(ComposedTransactionalComponentClass.class, Transactional.class)).isTrue();
assertThat(isAnnotated(ComposedTransactionalComponentClass.class, Component.class)).isTrue();
assertThat(isAnnotated(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class)).isTrue();
}
@Test
public void isAnnotatedForPlainTypes() {
assertTrue(isAnnotated(Order.class, Documented.class));
assertTrue(isAnnotated(NonNullApi.class, Documented.class));
assertTrue(isAnnotated(NonNullApi.class, Nonnull.class));
assertTrue(isAnnotated(ParametersAreNonnullByDefault.class, Nonnull.class));
assertThat(isAnnotated(Order.class, Documented.class)).isTrue();
assertThat(isAnnotated(NonNullApi.class, Documented.class)).isTrue();
assertThat(isAnnotated(NonNullApi.class, Nonnull.class)).isTrue();
assertThat(isAnnotated(ParametersAreNonnullByDefault.class, Nonnull.class)).isTrue();
}
@Test
public void isAnnotatedWithNameOnNonAnnotatedClass() {
assertFalse(isAnnotated(NonAnnotatedClass.class, TX_NAME));
assertThat(isAnnotated(NonAnnotatedClass.class, TX_NAME)).isFalse();
}
@Test
public void isAnnotatedWithNameOnClassWithMetaDepth() {
assertTrue(isAnnotated(TransactionalComponentClass.class, TransactionalComponent.class.getName()));
assertFalse("isAnnotated() does not search the class hierarchy.",
isAnnotated(SubTransactionalComponentClass.class, TransactionalComponent.class.getName()));
assertTrue(isAnnotated(TransactionalComponentClass.class, TX_NAME));
assertTrue(isAnnotated(TransactionalComponentClass.class, Component.class.getName()));
assertTrue(isAnnotated(ComposedTransactionalComponentClass.class, TX_NAME));
assertTrue(isAnnotated(ComposedTransactionalComponentClass.class, Component.class.getName()));
assertTrue(isAnnotated(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class.getName()));
assertThat(isAnnotated(TransactionalComponentClass.class, TransactionalComponent.class.getName())).isTrue();
assertThat(isAnnotated(SubTransactionalComponentClass.class, TransactionalComponent.class.getName())).as("isAnnotated() does not search the class hierarchy.").isFalse();
assertThat(isAnnotated(TransactionalComponentClass.class, TX_NAME)).isTrue();
assertThat(isAnnotated(TransactionalComponentClass.class, Component.class.getName())).isTrue();
assertThat(isAnnotated(ComposedTransactionalComponentClass.class, TX_NAME)).isTrue();
assertThat(isAnnotated(ComposedTransactionalComponentClass.class, Component.class.getName())).isTrue();
assertThat(isAnnotated(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class.getName())).isTrue();
}
@Test
public void hasAnnotationOnNonAnnotatedClass() {
assertFalse(hasAnnotation(NonAnnotatedClass.class, Transactional.class));
assertThat(hasAnnotation(NonAnnotatedClass.class, Transactional.class)).isFalse();
}
@Test
public void hasAnnotationOnClassWithMetaDepth() {
assertTrue(hasAnnotation(TransactionalComponentClass.class, TransactionalComponent.class));
assertTrue(hasAnnotation(SubTransactionalComponentClass.class, TransactionalComponent.class));
assertTrue(hasAnnotation(TransactionalComponentClass.class, Transactional.class));
assertTrue(hasAnnotation(TransactionalComponentClass.class, Component.class));
assertTrue(hasAnnotation(ComposedTransactionalComponentClass.class, Transactional.class));
assertTrue(hasAnnotation(ComposedTransactionalComponentClass.class, Component.class));
assertTrue(hasAnnotation(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class));
assertThat(hasAnnotation(TransactionalComponentClass.class, TransactionalComponent.class)).isTrue();
assertThat(hasAnnotation(SubTransactionalComponentClass.class, TransactionalComponent.class)).isTrue();
assertThat(hasAnnotation(TransactionalComponentClass.class, Transactional.class)).isTrue();
assertThat(hasAnnotation(TransactionalComponentClass.class, Component.class)).isTrue();
assertThat(hasAnnotation(ComposedTransactionalComponentClass.class, Transactional.class)).isTrue();
assertThat(hasAnnotation(ComposedTransactionalComponentClass.class, Component.class)).isTrue();
assertThat(hasAnnotation(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class)).isTrue();
}
@Test
public void hasAnnotationForPlainTypes() {
assertTrue(hasAnnotation(Order.class, Documented.class));
assertTrue(hasAnnotation(NonNullApi.class, Documented.class));
assertTrue(hasAnnotation(NonNullApi.class, Nonnull.class));
assertTrue(hasAnnotation(ParametersAreNonnullByDefault.class, Nonnull.class));
assertThat(hasAnnotation(Order.class, Documented.class)).isTrue();
assertThat(hasAnnotation(NonNullApi.class, Documented.class)).isTrue();
assertThat(hasAnnotation(NonNullApi.class, Nonnull.class)).isTrue();
assertThat(hasAnnotation(ParametersAreNonnullByDefault.class, Nonnull.class)).isTrue();
}
@Test
public void getAllAnnotationAttributesOnNonAnnotatedClass() {
assertNull(getAllAnnotationAttributes(NonAnnotatedClass.class, TX_NAME));
assertThat(getAllAnnotationAttributes(NonAnnotatedClass.class, TX_NAME)).isNull();
}
@Test
public void getAllAnnotationAttributesOnClassWithLocalAnnotation() {
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(TxConfig.class, TX_NAME);
assertNotNull("Annotation attributes map for @Transactional on TxConfig", attributes);
assertEquals("value for TxConfig", asList("TxConfig"), attributes.get("value"));
assertThat(attributes).as("Annotation attributes map for @Transactional on TxConfig").isNotNull();
assertThat(attributes.get("value")).as("value for TxConfig").isEqualTo(asList("TxConfig"));
}
@Test
public void getAllAnnotationAttributesOnClassWithLocalComposedAnnotationAndInheritedAnnotation() {
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(SubClassWithInheritedAnnotation.class, TX_NAME);
assertNotNull("Annotation attributes map for @Transactional on SubClassWithInheritedAnnotation", attributes);
assertEquals(asList("composed2", "transactionManager"), attributes.get("qualifier"));
assertThat(attributes).as("Annotation attributes map for @Transactional on SubClassWithInheritedAnnotation").isNotNull();
assertThat(attributes.get("qualifier")).isEqualTo(asList("composed2", "transactionManager"));
}
@Test
public void getAllAnnotationAttributesFavorsInheritedAnnotationsOverMoreLocallyDeclaredComposedAnnotations() {
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(SubSubClassWithInheritedAnnotation.class, TX_NAME);
assertNotNull("Annotation attributes map for @Transactional on SubSubClassWithInheritedAnnotation", attributes);
assertEquals(asList("transactionManager"), attributes.get("qualifier"));
assertThat(attributes).as("Annotation attributes map for @Transactional on SubSubClassWithInheritedAnnotation").isNotNull();
assertThat(attributes.get("qualifier")).isEqualTo(asList("transactionManager"));
}
@Test
public void getAllAnnotationAttributesFavorsInheritedComposedAnnotationsOverMoreLocallyDeclaredComposedAnnotations() {
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes( SubSubClassWithInheritedComposedAnnotation.class, TX_NAME);
assertNotNull("Annotation attributes map for @Transactional on SubSubClassWithInheritedComposedAnnotation", attributes);
assertEquals(asList("composed1"), attributes.get("qualifier"));
assertThat(attributes).as("Annotation attributes map for @Transactional on SubSubClassWithInheritedComposedAnnotation").isNotNull();
assertThat(attributes.get("qualifier")).isEqualTo(asList("composed1"));
}
/**
@@ -249,8 +241,8 @@ public class AnnotatedElementUtilsTests {
public void getAllAnnotationAttributesOnClassWithLocalAnnotationThatShadowsAnnotationFromSuperclass() {
// See org.springframework.core.env.EnvironmentSystemIntegrationTests#mostSpecificDerivedClassDrivesEnvironment_withDevEnvAndDerivedDevConfigClass
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(DerivedTxConfig.class, TX_NAME);
assertNotNull("Annotation attributes map for @Transactional on DerivedTxConfig", attributes);
assertEquals("value for DerivedTxConfig", asList("DerivedTxConfig"), attributes.get("value"));
assertThat(attributes).as("Annotation attributes map for @Transactional on DerivedTxConfig").isNotNull();
assertThat(attributes.get("value")).as("value for DerivedTxConfig").isEqualTo(asList("DerivedTxConfig"));
}
/**
@@ -260,25 +252,24 @@ public class AnnotatedElementUtilsTests {
public void getAllAnnotationAttributesOnClassWithMultipleComposedAnnotations() {
// See org.springframework.core.env.EnvironmentSystemIntegrationTests
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(TxFromMultipleComposedAnnotations.class, TX_NAME);
assertNotNull("Annotation attributes map for @Transactional on TxFromMultipleComposedAnnotations", attributes);
assertEquals("value for TxFromMultipleComposedAnnotations.", asList("TxInheritedComposed", "TxComposed"),
attributes.get("value"));
assertThat(attributes).as("Annotation attributes map for @Transactional on TxFromMultipleComposedAnnotations").isNotNull();
assertThat(attributes.get("value")).as("value for TxFromMultipleComposedAnnotations.").isEqualTo(asList("TxInheritedComposed", "TxComposed"));
}
@Test
public void getAllAnnotationAttributesOnLangType() {
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(
NonNullApi.class, Nonnull.class.getName());
assertNotNull("Annotation attributes map for @Nonnull on NonNullApi", attributes);
assertEquals("value for NonNullApi", asList(When.ALWAYS), attributes.get("when"));
assertThat(attributes).as("Annotation attributes map for @Nonnull on NonNullApi").isNotNull();
assertThat(attributes.get("when")).as("value for NonNullApi").isEqualTo(asList(When.ALWAYS));
}
@Test
public void getAllAnnotationAttributesOnJavaxType() {
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(
ParametersAreNonnullByDefault.class, Nonnull.class.getName());
assertNotNull("Annotation attributes map for @Nonnull on NonNullApi", attributes);
assertEquals("value for NonNullApi", asList(When.ALWAYS), attributes.get("when"));
assertThat(attributes).as("Annotation attributes map for @Nonnull on NonNullApi").isNotNull();
assertThat(attributes.get("when")).as("value for NonNullApi").isEqualTo(asList(When.ALWAYS));
}
@Test
@@ -286,10 +277,10 @@ public class AnnotatedElementUtilsTests {
Class<?> element = TxConfig.class;
String name = TX_NAME;
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertNotNull("Annotation attributes for @Transactional on TxConfig", attributes);
assertEquals("value for TxConfig", "TxConfig", attributes.getString("value"));
assertThat(attributes).as("Annotation attributes for @Transactional on TxConfig").isNotNull();
assertThat(attributes.getString("value")).as("value for TxConfig").isEqualTo("TxConfig");
// Verify contracts between utility methods:
assertTrue(isAnnotated(element, name));
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
@@ -297,16 +288,16 @@ public class AnnotatedElementUtilsTests {
Class<?> element = DerivedTxConfig.class;
String name = TX_NAME;
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertNotNull("Annotation attributes for @Transactional on DerivedTxConfig", attributes);
assertEquals("value for DerivedTxConfig", "DerivedTxConfig", attributes.getString("value"));
assertThat(attributes).as("Annotation attributes for @Transactional on DerivedTxConfig").isNotNull();
assertThat(attributes.getString("value")).as("value for DerivedTxConfig").isEqualTo("DerivedTxConfig");
// Verify contracts between utility methods:
assertTrue(isAnnotated(element, name));
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
public void getMergedAnnotationAttributesOnMetaCycleAnnotatedClassWithMissingTargetMetaAnnotation() {
AnnotationAttributes attributes = getMergedAnnotationAttributes(MetaCycleAnnotatedClass.class, TX_NAME);
assertNull("Should not find annotation attributes for @Transactional on MetaCycleAnnotatedClass", attributes);
assertThat(attributes).as("Should not find annotation attributes for @Transactional on MetaCycleAnnotatedClass").isNull();
}
@Test
@@ -314,10 +305,10 @@ public class AnnotatedElementUtilsTests {
Class<?> element = SubClassWithInheritedAnnotation.class;
String name = TX_NAME;
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertNotNull("AnnotationAttributes for @Transactional on SubClassWithInheritedAnnotation", attributes);
assertThat(attributes).as("AnnotationAttributes for @Transactional on SubClassWithInheritedAnnotation").isNotNull();
// Verify contracts between utility methods:
assertTrue(isAnnotated(element, name));
assertTrue("readOnly flag for SubClassWithInheritedAnnotation.", attributes.getBoolean("readOnly"));
assertThat(isAnnotated(element, name)).isTrue();
assertThat(attributes.getBoolean("readOnly")).as("readOnly flag for SubClassWithInheritedAnnotation.").isTrue();
}
@Test
@@ -325,10 +316,10 @@ public class AnnotatedElementUtilsTests {
Class<?> element = SubSubClassWithInheritedAnnotation.class;
String name = TX_NAME;
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertNotNull("AnnotationAttributes for @Transactional on SubSubClassWithInheritedAnnotation", attributes);
assertThat(attributes).as("AnnotationAttributes for @Transactional on SubSubClassWithInheritedAnnotation").isNotNull();
// Verify contracts between utility methods:
assertTrue(isAnnotated(element, name));
assertFalse("readOnly flag for SubSubClassWithInheritedAnnotation.", attributes.getBoolean("readOnly"));
assertThat(isAnnotated(element, name)).isTrue();
assertThat(attributes.getBoolean("readOnly")).as("readOnly flag for SubSubClassWithInheritedAnnotation.").isFalse();
}
@Test
@@ -336,10 +327,10 @@ public class AnnotatedElementUtilsTests {
Class<?> element = SubSubClassWithInheritedComposedAnnotation.class;
String name = TX_NAME;
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertNotNull("AnnotationAttributes for @Transactional on SubSubClassWithInheritedComposedAnnotation.", attributes);
assertThat(attributes).as("AnnotationAttributes for @Transactional on SubSubClassWithInheritedComposedAnnotation.").isNotNull();
// Verify contracts between utility methods:
assertTrue(isAnnotated(element, name));
assertFalse("readOnly flag for SubSubClassWithInheritedComposedAnnotation.", attributes.getBoolean("readOnly"));
assertThat(isAnnotated(element, name)).isTrue();
assertThat(attributes.getBoolean("readOnly")).as("readOnly flag for SubSubClassWithInheritedComposedAnnotation.").isFalse();
}
@Test
@@ -347,9 +338,9 @@ public class AnnotatedElementUtilsTests {
Class<?> element = ConcreteClassWithInheritedAnnotation.class;
String name = TX_NAME;
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertNull("Should not find @Transactional on ConcreteClassWithInheritedAnnotation", attributes);
assertThat(attributes).as("Should not find @Transactional on ConcreteClassWithInheritedAnnotation").isNull();
// Verify contracts between utility methods:
assertFalse(isAnnotated(element, name));
assertThat(isAnnotated(element, name)).isFalse();
}
@Test
@@ -357,9 +348,9 @@ public class AnnotatedElementUtilsTests {
Class<?> element = InheritedAnnotationInterface.class;
String name = TX_NAME;
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertNotNull("Should find @Transactional on InheritedAnnotationInterface", attributes);
assertThat(attributes).as("Should find @Transactional on InheritedAnnotationInterface").isNotNull();
// Verify contracts between utility methods:
assertTrue(isAnnotated(element, name));
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
@@ -367,9 +358,9 @@ public class AnnotatedElementUtilsTests {
Class<?> element = NonInheritedAnnotationInterface.class;
String name = Order.class.getName();
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertNotNull("Should find @Order on NonInheritedAnnotationInterface", attributes);
assertThat(attributes).as("Should find @Order on NonInheritedAnnotationInterface").isNotNull();
// Verify contracts between utility methods:
assertTrue(isAnnotated(element, name));
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
@@ -378,12 +369,12 @@ public class AnnotatedElementUtilsTests {
String name = ContextConfig.class.getName();
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertNotNull("Should find @ContextConfig on " + element.getSimpleName(), attributes);
assertArrayEquals("locations", asArray("explicitDeclaration"), attributes.getStringArray("locations"));
assertArrayEquals("value", asArray("explicitDeclaration"), attributes.getStringArray("value"));
assertThat(attributes).as("Should find @ContextConfig on " + element.getSimpleName()).isNotNull();
assertThat(attributes.getStringArray("locations")).as("locations").isEqualTo(asArray("explicitDeclaration"));
assertThat(attributes.getStringArray("value")).as("value").isEqualTo(asArray("explicitDeclaration"));
// Verify contracts between utility methods:
assertTrue(isAnnotated(element, name));
assertThat(isAnnotated(element, name)).isTrue();
}
/**
@@ -409,12 +400,12 @@ public class AnnotatedElementUtilsTests {
String simpleName = clazz.getSimpleName();
AnnotationAttributes attributes = getMergedAnnotationAttributes(clazz, name);
assertNotNull("Should find @ContextConfig on " + simpleName, attributes);
assertArrayEquals("locations for class [" + clazz.getSimpleName() + "]", expected, attributes.getStringArray("locations"));
assertArrayEquals("value for class [" + clazz.getSimpleName() + "]", expected, attributes.getStringArray("value"));
assertThat(attributes).as("Should find @ContextConfig on " + simpleName).isNotNull();
assertThat(attributes.getStringArray("locations")).as("locations for class [" + clazz.getSimpleName() + "]").isEqualTo(expected);
assertThat(attributes.getStringArray("value")).as("value for class [" + clazz.getSimpleName() + "]").isEqualTo(expected);
// Verify contracts between utility methods:
assertTrue(isAnnotated(clazz, name));
assertThat(isAnnotated(clazz, name)).isTrue();
}
@Test
@@ -423,12 +414,12 @@ public class AnnotatedElementUtilsTests {
String name = ContextConfig.class.getName();
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertNotNull("Should find @ContextConfig on " + element.getSimpleName(), attributes);
assertArrayEquals("value", asArray("test.xml"), attributes.getStringArray("value"));
assertArrayEquals("locations", asArray("test.xml"), attributes.getStringArray("locations"));
assertThat(attributes).as("Should find @ContextConfig on " + element.getSimpleName()).isNotNull();
assertThat(attributes.getStringArray("value")).as("value").isEqualTo(asArray("test.xml"));
assertThat(attributes.getStringArray("locations")).as("locations").isEqualTo(asArray("test.xml"));
// Verify contracts between utility methods:
assertTrue(isAnnotated(element, name));
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
@@ -437,12 +428,12 @@ public class AnnotatedElementUtilsTests {
String name = ContextConfig.class.getName();
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertNotNull("Should find @ContextConfig on " + element.getSimpleName(), attributes);
assertArrayEquals("locations", asArray("test.xml"), attributes.getStringArray("locations"));
assertArrayEquals("value", asArray("test.xml"), attributes.getStringArray("value"));
assertThat(attributes).as("Should find @ContextConfig on " + element.getSimpleName()).isNotNull();
assertThat(attributes.getStringArray("locations")).as("locations").isEqualTo(asArray("test.xml"));
assertThat(attributes.getStringArray("value")).as("value").isEqualTo(asArray("test.xml"));
// Verify contracts between utility methods:
assertTrue(isAnnotated(element, name));
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
@@ -452,14 +443,14 @@ public class AnnotatedElementUtilsTests {
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
String[] expected = asArray("A.xml", "B.xml");
assertNotNull("Should find @ImplicitAliasesContextConfig on " + element.getSimpleName(), attributes);
assertArrayEquals("groovyScripts", expected, attributes.getStringArray("groovyScripts"));
assertArrayEquals("xmlFiles", expected, attributes.getStringArray("xmlFiles"));
assertArrayEquals("locations", expected, attributes.getStringArray("locations"));
assertArrayEquals("value", expected, attributes.getStringArray("value"));
assertThat(attributes).as("Should find @ImplicitAliasesContextConfig on " + element.getSimpleName()).isNotNull();
assertThat(attributes.getStringArray("groovyScripts")).as("groovyScripts").isEqualTo(expected);
assertThat(attributes.getStringArray("xmlFiles")).as("xmlFiles").isEqualTo(expected);
assertThat(attributes.getStringArray("locations")).as("locations").isEqualTo(expected);
assertThat(attributes.getStringArray("value")).as("value").isEqualTo(expected);
// Verify contracts between utility methods:
assertTrue(isAnnotated(element, name));
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
@@ -498,13 +489,14 @@ public class AnnotatedElementUtilsTests {
String name = ContextConfig.class.getName();
ContextConfig contextConfig = getMergedAnnotation(element, ContextConfig.class);
assertNotNull("Should find @ContextConfig on " + element.getSimpleName(), contextConfig);
assertArrayEquals("locations", expected, contextConfig.locations());
assertArrayEquals("value", expected, contextConfig.value());
assertArrayEquals("classes", new Class<?>[0], contextConfig.classes());
assertThat(contextConfig).as("Should find @ContextConfig on " + element.getSimpleName()).isNotNull();
assertThat(contextConfig.locations()).as("locations").isEqualTo(expected);
assertThat(contextConfig.value()).as("value").isEqualTo(expected);
Object[] expecteds = new Class<?>[0];
assertThat(contextConfig.classes()).as("classes").isEqualTo(expecteds);
// Verify contracts between utility methods:
assertTrue(isAnnotated(element, name));
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
@@ -514,14 +506,14 @@ public class AnnotatedElementUtilsTests {
ImplicitAliasesContextConfig config = getMergedAnnotation(element, ImplicitAliasesContextConfig.class);
String[] expected = asArray("A.xml", "B.xml");
assertNotNull("Should find @ImplicitAliasesContextConfig on " + element.getSimpleName(), config);
assertArrayEquals("groovyScripts", expected, config.groovyScripts());
assertArrayEquals("xmlFiles", expected, config.xmlFiles());
assertArrayEquals("locations", expected, config.locations());
assertArrayEquals("value", expected, config.value());
assertThat(config).as("Should find @ImplicitAliasesContextConfig on " + element.getSimpleName()).isNotNull();
assertThat(config.groovyScripts()).as("groovyScripts").isEqualTo(expected);
assertThat(config.xmlFiles()).as("xmlFiles").isEqualTo(expected);
assertThat(config.locations()).as("locations").isEqualTo(expected);
assertThat(config.value()).as("value").isEqualTo(expected);
// Verify contracts between utility methods:
assertTrue(isAnnotated(element, name));
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
@@ -541,66 +533,66 @@ public class AnnotatedElementUtilsTests {
String[] expected = asArray("test.xml");
assertNotNull("Should find @ContextConfig on " + element.getSimpleName(), attributes);
assertArrayEquals("locations", expected, attributes.getStringArray("locations"));
assertArrayEquals("value", expected, attributes.getStringArray("value"));
assertThat(attributes).as("Should find @ContextConfig on " + element.getSimpleName()).isNotNull();
assertThat(attributes.getStringArray("locations")).as("locations").isEqualTo(expected);
assertThat(attributes.getStringArray("value")).as("value").isEqualTo(expected);
}
@Test
public void findMergedAnnotationAttributesOnInheritedAnnotationInterface() {
AnnotationAttributes attributes = findMergedAnnotationAttributes(InheritedAnnotationInterface.class, Transactional.class);
assertNotNull("Should find @Transactional on InheritedAnnotationInterface", attributes);
assertThat(attributes).as("Should find @Transactional on InheritedAnnotationInterface").isNotNull();
}
@Test
public void findMergedAnnotationAttributesOnSubInheritedAnnotationInterface() {
AnnotationAttributes attributes = findMergedAnnotationAttributes(SubInheritedAnnotationInterface.class, Transactional.class);
assertNotNull("Should find @Transactional on SubInheritedAnnotationInterface", attributes);
assertThat(attributes).as("Should find @Transactional on SubInheritedAnnotationInterface").isNotNull();
}
@Test
public void findMergedAnnotationAttributesOnSubSubInheritedAnnotationInterface() {
AnnotationAttributes attributes = findMergedAnnotationAttributes(SubSubInheritedAnnotationInterface.class, Transactional.class);
assertNotNull("Should find @Transactional on SubSubInheritedAnnotationInterface", attributes);
assertThat(attributes).as("Should find @Transactional on SubSubInheritedAnnotationInterface").isNotNull();
}
@Test
public void findMergedAnnotationAttributesOnNonInheritedAnnotationInterface() {
AnnotationAttributes attributes = findMergedAnnotationAttributes(NonInheritedAnnotationInterface.class, Order.class);
assertNotNull("Should find @Order on NonInheritedAnnotationInterface", attributes);
assertThat(attributes).as("Should find @Order on NonInheritedAnnotationInterface").isNotNull();
}
@Test
public void findMergedAnnotationAttributesOnSubNonInheritedAnnotationInterface() {
AnnotationAttributes attributes = findMergedAnnotationAttributes(SubNonInheritedAnnotationInterface.class, Order.class);
assertNotNull("Should find @Order on SubNonInheritedAnnotationInterface", attributes);
assertThat(attributes).as("Should find @Order on SubNonInheritedAnnotationInterface").isNotNull();
}
@Test
public void findMergedAnnotationAttributesOnSubSubNonInheritedAnnotationInterface() {
AnnotationAttributes attributes = findMergedAnnotationAttributes(SubSubNonInheritedAnnotationInterface.class, Order.class);
assertNotNull("Should find @Order on SubSubNonInheritedAnnotationInterface", attributes);
assertThat(attributes).as("Should find @Order on SubSubNonInheritedAnnotationInterface").isNotNull();
}
@Test
public void findMergedAnnotationAttributesInheritedFromInterfaceMethod() throws NoSuchMethodException {
Method method = ConcreteClassWithInheritedAnnotation.class.getMethod("handleFromInterface");
AnnotationAttributes attributes = findMergedAnnotationAttributes(method, Order.class);
assertNotNull("Should find @Order on ConcreteClassWithInheritedAnnotation.handleFromInterface() method", attributes);
assertThat(attributes).as("Should find @Order on ConcreteClassWithInheritedAnnotation.handleFromInterface() method").isNotNull();
}
@Test
public void findMergedAnnotationAttributesInheritedFromAbstractMethod() throws NoSuchMethodException {
Method method = ConcreteClassWithInheritedAnnotation.class.getMethod("handle");
AnnotationAttributes attributes = findMergedAnnotationAttributes(method, Transactional.class);
assertNotNull("Should find @Transactional on ConcreteClassWithInheritedAnnotation.handle() method", attributes);
assertThat(attributes).as("Should find @Transactional on ConcreteClassWithInheritedAnnotation.handle() method").isNotNull();
}
@Test
public void findMergedAnnotationAttributesInheritedFromBridgedMethod() throws NoSuchMethodException {
Method method = ConcreteClassWithInheritedAnnotation.class.getMethod("handleParameterized", String.class);
AnnotationAttributes attributes = findMergedAnnotationAttributes(method, Transactional.class);
assertNotNull("Should find @Transactional on bridged ConcreteClassWithInheritedAnnotation.handleParameterized()", attributes);
assertThat(attributes).as("Should find @Transactional on bridged ConcreteClassWithInheritedAnnotation.handleParameterized()").isNotNull();
}
/**
@@ -624,18 +616,19 @@ public class AnnotatedElementUtilsTests {
}
}
}
assertTrue(bridgeMethod != null && bridgeMethod.isBridge());
assertTrue(bridgedMethod != null && !bridgedMethod.isBridge());
assertThat(bridgeMethod != null && bridgeMethod.isBridge()).isTrue();
boolean condition = bridgedMethod != null && !bridgedMethod.isBridge();
assertThat(condition).isTrue();
AnnotationAttributes attributes = findMergedAnnotationAttributes(bridgeMethod, Order.class);
assertNotNull("Should find @Order on StringGenericParameter.getFor() bridge method", attributes);
assertThat(attributes).as("Should find @Order on StringGenericParameter.getFor() bridge method").isNotNull();
}
@Test
public void findMergedAnnotationAttributesOnClassWithMetaAndLocalTxConfig() {
AnnotationAttributes attributes = findMergedAnnotationAttributes(MetaAndLocalTxConfigClass.class, Transactional.class);
assertNotNull("Should find @Transactional on MetaAndLocalTxConfigClass", attributes);
assertEquals("TX qualifier for MetaAndLocalTxConfigClass.", "localTxMgr", attributes.getString("qualifier"));
assertThat(attributes).as("Should find @Transactional on MetaAndLocalTxConfigClass").isNotNull();
assertThat(attributes.getString("qualifier")).as("TX qualifier for MetaAndLocalTxConfigClass.").isEqualTo("localTxMgr");
}
@Test
@@ -645,18 +638,18 @@ public class AnnotatedElementUtilsTests {
// 1) Find and merge AnnotationAttributes from the annotation hierarchy
AnnotationAttributes attributes = findMergedAnnotationAttributes(
AliasedTransactionalComponentClass.class, AliasedTransactional.class);
assertNotNull("@AliasedTransactional on AliasedTransactionalComponentClass.", attributes);
assertThat(attributes).as("@AliasedTransactional on AliasedTransactionalComponentClass.").isNotNull();
// 2) Synthesize the AnnotationAttributes back into the target annotation
AliasedTransactional annotation = AnnotationUtils.synthesizeAnnotation(attributes,
AliasedTransactional.class, AliasedTransactionalComponentClass.class);
assertNotNull(annotation);
assertThat(annotation).isNotNull();
// 3) Verify that the AnnotationAttributes and synthesized annotation are equivalent
assertEquals("TX value via attributes.", qualifier, attributes.getString("value"));
assertEquals("TX value via synthesized annotation.", qualifier, annotation.value());
assertEquals("TX qualifier via attributes.", qualifier, attributes.getString("qualifier"));
assertEquals("TX qualifier via synthesized annotation.", qualifier, annotation.qualifier());
assertThat(attributes.getString("value")).as("TX value via attributes.").isEqualTo(qualifier);
assertThat(annotation.value()).as("TX value via synthesized annotation.").isEqualTo(qualifier);
assertThat(attributes.getString("qualifier")).as("TX qualifier via attributes.").isEqualTo(qualifier);
assertThat(annotation.qualifier()).as("TX qualifier via synthesized annotation.").isEqualTo(qualifier);
}
@Test
@@ -664,10 +657,10 @@ public class AnnotatedElementUtilsTests {
AnnotationAttributes attributes = assertComponentScanAttributes(TestComponentScanClass.class, "com.example.app.test");
Filter[] excludeFilters = attributes.getAnnotationArray("excludeFilters", Filter.class);
assertNotNull(excludeFilters);
assertThat(excludeFilters).isNotNull();
List<String> patterns = stream(excludeFilters).map(Filter::pattern).collect(toList());
assertEquals(asList("*Test", "*Tests"), patterns);
assertThat(patterns).isEqualTo(asList("*Test", "*Tests"));
}
/**
@@ -693,9 +686,9 @@ public class AnnotatedElementUtilsTests {
private AnnotationAttributes assertComponentScanAttributes(Class<?> element, String... expected) {
AnnotationAttributes attributes = findMergedAnnotationAttributes(element, ComponentScan.class);
assertNotNull("Should find @ComponentScan on " + element, attributes);
assertArrayEquals("value: ", expected, attributes.getStringArray("value"));
assertArrayEquals("basePackages: ", expected, attributes.getStringArray("basePackages"));
assertThat(attributes).as("Should find @ComponentScan on " + element).isNotNull();
assertThat(attributes.getStringArray("value")).as("value: ").isEqualTo(expected);
assertThat(attributes.getStringArray("basePackages")).as("basePackages: ").isEqualTo(expected);
return attributes;
}
@@ -708,9 +701,9 @@ public class AnnotatedElementUtilsTests {
public void findMergedAnnotationWithAttributeAliasesInTargetAnnotation() {
Class<?> element = AliasedTransactionalComponentClass.class;
AliasedTransactional annotation = findMergedAnnotation(element, AliasedTransactional.class);
assertNotNull("@AliasedTransactional on " + element, annotation);
assertEquals("TX value via synthesized annotation.", "aliasForQualifier", annotation.value());
assertEquals("TX qualifier via synthesized annotation.", "aliasForQualifier", annotation.qualifier());
assertThat(annotation).as("@AliasedTransactional on " + element).isNotNull();
assertThat(annotation.value()).as("TX value via synthesized annotation.").isEqualTo("aliasForQualifier");
assertThat(annotation.qualifier()).as("TX qualifier via synthesized annotation.").isEqualTo("aliasForQualifier");
}
@Test
@@ -721,20 +714,20 @@ public class AnnotatedElementUtilsTests {
Class<?> element = AliasedComposedContextConfigAndTestPropSourceClass.class;
ContextConfig contextConfig = findMergedAnnotation(element, ContextConfig.class);
assertNotNull("@ContextConfig on " + element, contextConfig);
assertArrayEquals("locations", xmlLocations, contextConfig.locations());
assertArrayEquals("value", xmlLocations, contextConfig.value());
assertThat(contextConfig).as("@ContextConfig on " + element).isNotNull();
assertThat(contextConfig.locations()).as("locations").isEqualTo(xmlLocations);
assertThat(contextConfig.value()).as("value").isEqualTo(xmlLocations);
// Synthesized annotation
TestPropSource testPropSource = AnnotationUtils.findAnnotation(element, TestPropSource.class);
assertArrayEquals("locations", propFiles, testPropSource.locations());
assertArrayEquals("value", propFiles, testPropSource.value());
assertThat(testPropSource.locations()).as("locations").isEqualTo(propFiles);
assertThat(testPropSource.value()).as("value").isEqualTo(propFiles);
// Merged annotation
testPropSource = findMergedAnnotation(element, TestPropSource.class);
assertNotNull("@TestPropSource on " + element, testPropSource);
assertArrayEquals("locations", propFiles, testPropSource.locations());
assertArrayEquals("value", propFiles, testPropSource.value());
assertThat(testPropSource).as("@TestPropSource on " + element).isNotNull();
assertThat(testPropSource.locations()).as("locations").isEqualTo(propFiles);
assertThat(testPropSource.value()).as("value").isEqualTo(propFiles);
}
@Test
@@ -743,11 +736,11 @@ public class AnnotatedElementUtilsTests {
Class<?> element = SpringAppConfigClass.class;
ContextConfig contextConfig = findMergedAnnotation(element, ContextConfig.class);
assertNotNull("Should find @ContextConfig on " + element, contextConfig);
assertArrayEquals("locations for " + element, EMPTY, contextConfig.locations());
assertThat(contextConfig).as("Should find @ContextConfig on " + element).isNotNull();
assertThat(contextConfig.locations()).as("locations for " + element).isEqualTo(EMPTY);
// 'value' in @SpringAppConfig should not override 'value' in @ContextConfig
assertArrayEquals("value for " + element, EMPTY, contextConfig.value());
assertArrayEquals("classes for " + element, new Class<?>[] {Number.class}, contextConfig.classes());
assertThat(contextConfig.value()).as("value for " + element).isEqualTo(EMPTY);
assertThat(contextConfig.classes()).as("classes for " + element).isEqualTo(new Class<?>[] {Number.class});
}
@Test
@@ -763,63 +756,57 @@ public class AnnotatedElementUtilsTests {
private void assertWebMapping(AnnotatedElement element) throws ArrayComparisonFailure {
WebMapping webMapping = findMergedAnnotation(element, WebMapping.class);
assertNotNull(webMapping);
assertArrayEquals("value attribute: ", asArray("/test"), webMapping.value());
assertArrayEquals("path attribute: ", asArray("/test"), webMapping.path());
assertThat(webMapping).isNotNull();
assertThat(webMapping.value()).as("value attribute: ").isEqualTo(asArray("/test"));
assertThat(webMapping.path()).as("path attribute: ").isEqualTo(asArray("/test"));
}
@Test
public void javaLangAnnotationTypeViaFindMergedAnnotation() throws Exception {
Constructor<?> deprecatedCtor = Date.class.getConstructor(String.class);
assertEquals(deprecatedCtor.getAnnotation(Deprecated.class),
findMergedAnnotation(deprecatedCtor, Deprecated.class));
assertEquals(Date.class.getAnnotation(Deprecated.class),
findMergedAnnotation(Date.class, Deprecated.class));
assertThat(findMergedAnnotation(deprecatedCtor, Deprecated.class)).isEqualTo(deprecatedCtor.getAnnotation(Deprecated.class));
assertThat(findMergedAnnotation(Date.class, Deprecated.class)).isEqualTo(Date.class.getAnnotation(Deprecated.class));
}
@Test
public void javaxAnnotationTypeViaFindMergedAnnotation() throws Exception {
assertEquals(ResourceHolder.class.getAnnotation(Resource.class),
findMergedAnnotation(ResourceHolder.class, Resource.class));
assertEquals(SpringAppConfigClass.class.getAnnotation(Resource.class),
findMergedAnnotation(SpringAppConfigClass.class, Resource.class));
assertThat(findMergedAnnotation(ResourceHolder.class, Resource.class)).isEqualTo(ResourceHolder.class.getAnnotation(Resource.class));
assertThat(findMergedAnnotation(SpringAppConfigClass.class, Resource.class)).isEqualTo(SpringAppConfigClass.class.getAnnotation(Resource.class));
}
@Test
public void nullableAnnotationTypeViaFindMergedAnnotation() throws Exception {
Method method = TransactionalServiceImpl.class.getMethod("doIt");
assertEquals(method.getAnnotation(Resource.class),
findMergedAnnotation(method, Resource.class));
assertEquals(method.getAnnotation(Resource.class),
findMergedAnnotation(method, Resource.class));
assertThat(findMergedAnnotation(method, Resource.class)).isEqualTo(method.getAnnotation(Resource.class));
assertThat(findMergedAnnotation(method, Resource.class)).isEqualTo(method.getAnnotation(Resource.class));
}
@Test
public void getAllMergedAnnotationsOnClassWithInterface() throws Exception {
Method method = TransactionalServiceImpl.class.getMethod("doIt");
Set<Transactional> allMergedAnnotations = getAllMergedAnnotations(method, Transactional.class);
assertTrue(allMergedAnnotations.isEmpty());
assertThat(allMergedAnnotations.isEmpty()).isTrue();
}
@Test
public void findAllMergedAnnotationsOnClassWithInterface() throws Exception {
Method method = TransactionalServiceImpl.class.getMethod("doIt");
Set<Transactional> allMergedAnnotations = findAllMergedAnnotations(method, Transactional.class);
assertEquals(1, allMergedAnnotations.size());
assertThat(allMergedAnnotations.size()).isEqualTo(1);
}
@Test // SPR-16060
public void findMethodAnnotationFromGenericInterface() throws Exception {
Method method = ImplementsInterfaceWithGenericAnnotatedMethod.class.getMethod("foo", String.class);
Order order = findMergedAnnotation(method, Order.class);
assertNotNull(order);
assertThat(order).isNotNull();
}
@Test // SPR-17146
public void findMethodAnnotationFromGenericSuperclass() throws Exception {
Method method = ExtendsBaseClassWithGenericAnnotatedMethod.class.getMethod("foo", String.class);
Order order = findMergedAnnotation(method, Order.class);
assertNotNull(order);
assertThat(order).isNotNull();
}
@Test // gh-22655

View File

@@ -27,10 +27,6 @@ import org.springframework.core.annotation.AnnotationUtilsTests.ImplicitAliasesC
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for {@link AnnotationAttributes}.
@@ -67,7 +63,7 @@ public class AnnotationAttributesTests {
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.getClass("class").equals(Integer.class)).isTrue();
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);
@@ -101,12 +97,12 @@ public class AnnotationAttributesTests {
assertThat(attributes.getClassArray("classes")).isEqualTo(new Class<?>[] {Number.class});
AnnotationAttributes[] array = attributes.getAnnotationArray("nestedAttributes");
assertNotNull(array);
assertThat(array).isNotNull();
assertThat(array.length).isEqualTo(1);
assertThat(array[0].getString("name")).isEqualTo("Dilbert");
Filter[] filters = attributes.getAnnotationArray("filters", Filter.class);
assertNotNull(filters);
assertThat(filters).isNotNull();
assertThat(filters.length).isEqualTo(1);
assertThat(filters[0].pattern()).isEqualTo("foo");
}
@@ -123,8 +119,8 @@ public class AnnotationAttributesTests {
assertThat(retrievedFilter.pattern()).isEqualTo("foo");
Filter[] retrievedFilters = attributes.getAnnotationArray("filters", Filter.class);
assertNotNull(retrievedFilters);
assertEquals(2, retrievedFilters.length);
assertThat(retrievedFilters).isNotNull();
assertThat(retrievedFilters.length).isEqualTo(2);
assertThat(retrievedFilters[1].pattern()).isEqualTo("foo");
}
@@ -165,12 +161,12 @@ public class AnnotationAttributesTests {
attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class);
attributes.put("value", value);
AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false);
aliases.stream().forEach(alias -> assertEquals(value, attributes.getString(alias)));
aliases.stream().forEach(alias -> assertThat(attributes.getString(alias)).isEqualTo(value));
attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class);
attributes.put("location1", value);
AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false);
aliases.stream().forEach(alias -> assertEquals(value, attributes.getString(alias)));
aliases.stream().forEach(alias -> assertThat(attributes.getString(alias)).isEqualTo(value));
attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class);
attributes.put("value", value);
@@ -178,7 +174,7 @@ public class AnnotationAttributesTests {
attributes.put("xmlFile", value);
attributes.put("groovyScript", value);
AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false);
aliases.stream().forEach(alias -> assertEquals(value, attributes.getString(alias)));
aliases.stream().forEach(alias -> assertThat(attributes.getString(alias)).isEqualTo(value));
}
@Test
@@ -189,35 +185,35 @@ public class AnnotationAttributesTests {
attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class);
attributes.put("location1", value);
AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false);
aliases.stream().forEach(alias -> assertArrayEquals(value, attributes.getStringArray(alias)));
aliases.stream().forEach(alias -> assertThat(attributes.getStringArray(alias)).isEqualTo(value));
attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class);
attributes.put("value", value);
AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false);
aliases.stream().forEach(alias -> assertArrayEquals(value, attributes.getStringArray(alias)));
aliases.stream().forEach(alias -> assertThat(attributes.getStringArray(alias)).isEqualTo(value));
attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class);
attributes.put("location1", value);
attributes.put("value", value);
AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false);
aliases.stream().forEach(alias -> assertArrayEquals(value, attributes.getStringArray(alias)));
aliases.stream().forEach(alias -> assertThat(attributes.getStringArray(alias)).isEqualTo(value));
attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class);
attributes.put("location1", value);
AnnotationUtils.registerDefaultValues(attributes);
AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false);
aliases.stream().forEach(alias -> assertArrayEquals(value, attributes.getStringArray(alias)));
aliases.stream().forEach(alias -> assertThat(attributes.getStringArray(alias)).isEqualTo(value));
attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class);
attributes.put("value", value);
AnnotationUtils.registerDefaultValues(attributes);
AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false);
aliases.stream().forEach(alias -> assertArrayEquals(value, attributes.getStringArray(alias)));
aliases.stream().forEach(alias -> assertThat(attributes.getStringArray(alias)).isEqualTo(value));
attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class);
AnnotationUtils.registerDefaultValues(attributes);
AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false);
aliases.stream().forEach(alias -> assertArrayEquals(new String[] {""}, attributes.getStringArray(alias)));
aliases.stream().forEach(alias -> assertThat(attributes.getStringArray(alias)).isEqualTo(new String[] {""}));
}

View File

@@ -23,9 +23,6 @@ import javax.annotation.Priority;
import org.junit.Test;
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;
/**
* @author Juergen Hoeller
@@ -44,8 +41,8 @@ public class AnnotationAwareOrderComparatorTests {
list.add(new B());
list.add(new A());
AnnotationAwareOrderComparator.sort(list);
assertTrue(list.get(0) instanceof A);
assertTrue(list.get(1) instanceof B);
assertThat(list.get(0) instanceof A).isTrue();
assertThat(list.get(1) instanceof B).isTrue();
}
@Test
@@ -54,8 +51,8 @@ public class AnnotationAwareOrderComparatorTests {
list.add(new B2());
list.add(new A2());
AnnotationAwareOrderComparator.sort(list);
assertTrue(list.get(0) instanceof A2);
assertTrue(list.get(1) instanceof B2);
assertThat(list.get(0) instanceof A2).isTrue();
assertThat(list.get(1) instanceof B2).isTrue();
}
@Test
@@ -64,8 +61,8 @@ public class AnnotationAwareOrderComparatorTests {
list.add(new B());
list.add(new A2());
AnnotationAwareOrderComparator.sort(list);
assertTrue(list.get(0) instanceof A2);
assertTrue(list.get(1) instanceof B);
assertThat(list.get(0) instanceof A2).isTrue();
assertThat(list.get(1) instanceof B).isTrue();
}
@Test
@@ -74,8 +71,8 @@ public class AnnotationAwareOrderComparatorTests {
list.add(new B());
list.add(new C());
AnnotationAwareOrderComparator.sort(list);
assertTrue(list.get(0) instanceof C);
assertTrue(list.get(1) instanceof B);
assertThat(list.get(0) instanceof C).isTrue();
assertThat(list.get(1) instanceof B).isTrue();
}
@Test
@@ -84,8 +81,8 @@ public class AnnotationAwareOrderComparatorTests {
list.add(B.class);
list.add(A.class);
AnnotationAwareOrderComparator.sort(list);
assertEquals(A.class, list.get(0));
assertEquals(B.class, list.get(1));
assertThat(list.get(0)).isEqualTo(A.class);
assertThat(list.get(1)).isEqualTo(B.class);
}
@Test
@@ -94,8 +91,8 @@ public class AnnotationAwareOrderComparatorTests {
list.add(B.class);
list.add(C.class);
AnnotationAwareOrderComparator.sort(list);
assertEquals(C.class, list.get(0));
assertEquals(B.class, list.get(1));
assertThat(list.get(0)).isEqualTo(C.class);
assertThat(list.get(1)).isEqualTo(B.class);
}
@Test
@@ -106,10 +103,10 @@ public class AnnotationAwareOrderComparatorTests {
list.add(null);
list.add(A.class);
AnnotationAwareOrderComparator.sort(list);
assertEquals(A.class, list.get(0));
assertEquals(B.class, list.get(1));
assertNull(list.get(2));
assertNull(list.get(3));
assertThat(list.get(0)).isEqualTo(A.class);
assertThat(list.get(1)).isEqualTo(B.class);
assertThat(list.get(2)).isNull();
assertThat(list.get(3)).isNull();
}

View File

@@ -29,10 +29,9 @@ import java.util.Set;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedRepeatableAnnotations;
import static org.springframework.core.annotation.AnnotatedElementUtils.getMergedRepeatableAnnotations;
@@ -112,8 +111,8 @@ public class ComposedRepeatableAnnotationsTests {
public void getNoninheritedComposedRepeatableAnnotationsOnSuperclass() {
Class<?> element = SubNoninheritedRepeatableClass.class;
Set<Noninherited> annotations = getMergedRepeatableAnnotations(element, Noninherited.class);
assertNotNull(annotations);
assertEquals(0, annotations.size());
assertThat(annotations).isNotNull();
assertThat(annotations.size()).isEqualTo(0);
}
@Test
@@ -213,39 +212,39 @@ public class ComposedRepeatableAnnotationsTests {
}
private void assertGetRepeatableAnnotations(AnnotatedElement element) {
assertNotNull(element);
assertThat(element).isNotNull();
Set<PeteRepeat> peteRepeats = getMergedRepeatableAnnotations(element, PeteRepeat.class);
assertNotNull(peteRepeats);
assertEquals(3, peteRepeats.size());
assertThat(peteRepeats).isNotNull();
assertThat(peteRepeats.size()).isEqualTo(3);
Iterator<PeteRepeat> iterator = peteRepeats.iterator();
assertEquals("A", iterator.next().value());
assertEquals("B", iterator.next().value());
assertEquals("C", iterator.next().value());
assertThat(iterator.next().value()).isEqualTo("A");
assertThat(iterator.next().value()).isEqualTo("B");
assertThat(iterator.next().value()).isEqualTo("C");
}
private void assertFindRepeatableAnnotations(AnnotatedElement element) {
assertNotNull(element);
assertThat(element).isNotNull();
Set<PeteRepeat> peteRepeats = findMergedRepeatableAnnotations(element, PeteRepeat.class);
assertNotNull(peteRepeats);
assertEquals(3, peteRepeats.size());
assertThat(peteRepeats).isNotNull();
assertThat(peteRepeats.size()).isEqualTo(3);
Iterator<PeteRepeat> iterator = peteRepeats.iterator();
assertEquals("A", iterator.next().value());
assertEquals("B", iterator.next().value());
assertEquals("C", iterator.next().value());
assertThat(iterator.next().value()).isEqualTo("A");
assertThat(iterator.next().value()).isEqualTo("B");
assertThat(iterator.next().value()).isEqualTo("C");
}
private void assertNoninheritedRepeatableAnnotations(Set<Noninherited> annotations) {
assertNotNull(annotations);
assertEquals(3, annotations.size());
assertThat(annotations).isNotNull();
assertThat(annotations.size()).isEqualTo(3);
Iterator<Noninherited> iterator = annotations.iterator();
assertEquals("A", iterator.next().value());
assertEquals("B", iterator.next().value());
assertEquals("C", iterator.next().value());
assertThat(iterator.next().value()).isEqualTo("A");
assertThat(iterator.next().value()).isEqualTo("B");
assertThat(iterator.next().value()).isEqualTo("C");
}

View File

@@ -29,9 +29,7 @@ import java.util.Set;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.core.annotation.AnnotatedElementUtils.findAllMergedAnnotations;
import static org.springframework.core.annotation.AnnotatedElementUtils.getAllMergedAnnotations;
@@ -63,22 +61,22 @@ public class MultipleComposedAnnotationsOnSingleAnnotatedElementTests {
public void getMultipleNoninheritedComposedAnnotationsOnClass() {
Class<?> element = MultipleNoninheritedComposedCachesClass.class;
Set<Cacheable> cacheables = getAllMergedAnnotations(element, Cacheable.class);
assertNotNull(cacheables);
assertEquals(2, cacheables.size());
assertThat(cacheables).isNotNull();
assertThat(cacheables.size()).isEqualTo(2);
Iterator<Cacheable> iterator = cacheables.iterator();
Cacheable cacheable1 = iterator.next();
Cacheable cacheable2 = iterator.next();
assertEquals("noninheritedCache1", cacheable1.value());
assertEquals("noninheritedCache2", cacheable2.value());
assertThat(cacheable1.value()).isEqualTo("noninheritedCache1");
assertThat(cacheable2.value()).isEqualTo("noninheritedCache2");
}
@Test
public void getMultipleNoninheritedComposedAnnotationsOnSuperclass() {
Class<?> element = SubMultipleNoninheritedComposedCachesClass.class;
Set<Cacheable> cacheables = getAllMergedAnnotations(element, Cacheable.class);
assertNotNull(cacheables);
assertEquals(0, cacheables.size());
assertThat(cacheables).isNotNull();
assertThat(cacheables.size()).isEqualTo(0);
}
@Test
@@ -90,8 +88,8 @@ public class MultipleComposedAnnotationsOnSingleAnnotatedElementTests {
public void getMultipleComposedAnnotationsOnInterface() {
Class<MultipleComposedCachesOnInterfaceClass> element = MultipleComposedCachesOnInterfaceClass.class;
Set<Cacheable> cacheables = getAllMergedAnnotations(element, Cacheable.class);
assertNotNull(cacheables);
assertEquals(0, cacheables.size());
assertThat(cacheables).isNotNull();
assertThat(cacheables.size()).isEqualTo(0);
}
@Test
@@ -110,8 +108,8 @@ public class MultipleComposedAnnotationsOnSingleAnnotatedElementTests {
@Ignore("Disabled since some Java 8 updates handle the bridge method differently")
public void getMultipleComposedAnnotationsOnBridgeMethod() throws Exception {
Set<Cacheable> cacheables = getAllMergedAnnotations(getBridgeMethod(), Cacheable.class);
assertNotNull(cacheables);
assertEquals(0, cacheables.size());
assertThat(cacheables).isNotNull();
assertThat(cacheables.size()).isEqualTo(0);
}
@Test
@@ -128,28 +126,28 @@ public class MultipleComposedAnnotationsOnSingleAnnotatedElementTests {
public void findMultipleNoninheritedComposedAnnotationsOnClass() {
Class<?> element = MultipleNoninheritedComposedCachesClass.class;
Set<Cacheable> cacheables = findAllMergedAnnotations(element, Cacheable.class);
assertNotNull(cacheables);
assertEquals(2, cacheables.size());
assertThat(cacheables).isNotNull();
assertThat(cacheables.size()).isEqualTo(2);
Iterator<Cacheable> iterator = cacheables.iterator();
Cacheable cacheable1 = iterator.next();
Cacheable cacheable2 = iterator.next();
assertEquals("noninheritedCache1", cacheable1.value());
assertEquals("noninheritedCache2", cacheable2.value());
assertThat(cacheable1.value()).isEqualTo("noninheritedCache1");
assertThat(cacheable2.value()).isEqualTo("noninheritedCache2");
}
@Test
public void findMultipleNoninheritedComposedAnnotationsOnSuperclass() {
Class<?> element = SubMultipleNoninheritedComposedCachesClass.class;
Set<Cacheable> cacheables = findAllMergedAnnotations(element, Cacheable.class);
assertNotNull(cacheables);
assertEquals(2, cacheables.size());
assertThat(cacheables).isNotNull();
assertThat(cacheables.size()).isEqualTo(2);
Iterator<Cacheable> iterator = cacheables.iterator();
Cacheable cacheable1 = iterator.next();
Cacheable cacheable2 = iterator.next();
assertEquals("noninheritedCache1", cacheable1.value());
assertEquals("noninheritedCache2", cacheable2.value());
assertThat(cacheable1.value()).isEqualTo("noninheritedCache1");
assertThat(cacheable2.value()).isEqualTo("noninheritedCache2");
}
@Test
@@ -203,42 +201,43 @@ public class MultipleComposedAnnotationsOnSingleAnnotatedElementTests {
}
}
}
assertTrue(bridgeMethod != null && bridgeMethod.isBridge());
assertTrue(bridgedMethod != null && !bridgedMethod.isBridge());
assertThat(bridgeMethod != null && bridgeMethod.isBridge()).isTrue();
boolean condition = bridgedMethod != null && !bridgedMethod.isBridge();
assertThat(condition).isTrue();
return bridgeMethod;
}
private void assertGetAllMergedAnnotationsBehavior(AnnotatedElement element) {
assertNotNull(element);
assertThat(element).isNotNull();
Set<Cacheable> cacheables = getAllMergedAnnotations(element, Cacheable.class);
assertNotNull(cacheables);
assertEquals(2, cacheables.size());
assertThat(cacheables).isNotNull();
assertThat(cacheables.size()).isEqualTo(2);
Iterator<Cacheable> iterator = cacheables.iterator();
Cacheable fooCacheable = iterator.next();
Cacheable barCacheable = iterator.next();
assertEquals("fooKey", fooCacheable.key());
assertEquals("fooCache", fooCacheable.value());
assertEquals("barKey", barCacheable.key());
assertEquals("barCache", barCacheable.value());
assertThat(fooCacheable.key()).isEqualTo("fooKey");
assertThat(fooCacheable.value()).isEqualTo("fooCache");
assertThat(barCacheable.key()).isEqualTo("barKey");
assertThat(barCacheable.value()).isEqualTo("barCache");
}
private void assertFindAllMergedAnnotationsBehavior(AnnotatedElement element) {
assertNotNull(element);
assertThat(element).isNotNull();
Set<Cacheable> cacheables = findAllMergedAnnotations(element, Cacheable.class);
assertNotNull(cacheables);
assertEquals(2, cacheables.size());
assertThat(cacheables).isNotNull();
assertThat(cacheables.size()).isEqualTo(2);
Iterator<Cacheable> iterator = cacheables.iterator();
Cacheable fooCacheable = iterator.next();
Cacheable barCacheable = iterator.next();
assertEquals("fooKey", fooCacheable.key());
assertEquals("fooCache", fooCacheable.value());
assertEquals("barKey", barCacheable.key());
assertEquals("barCache", barCacheable.value());
assertThat(fooCacheable.key()).isEqualTo("fooKey");
assertThat(fooCacheable.value()).isEqualTo("fooCache");
assertThat(barCacheable.key()).isEqualTo("barKey");
assertThat(barCacheable.value()).isEqualTo("barCache");
}

View File

@@ -25,8 +25,7 @@ import org.junit.Test;
import org.springframework.core.Ordered;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Stephane Nicoll
@@ -149,16 +148,16 @@ public class OrderSourceProviderTests {
private void assertOrder(List<?> actual, Object... expected) {
for (int i = 0; i < actual.size(); i++) {
assertSame("Wrong instance at index '" + i + "'", expected[i], actual.get(i));
assertThat(actual.get(i)).as("Wrong instance at index '" + i + "'").isSameAs(expected[i]);
}
assertEquals("Wrong number of items", expected.length, actual.size());
assertThat(actual.size()).as("Wrong number of items").isEqualTo(expected.length);
}
private void assertOrder(Object[] actual, Object... expected) {
for (int i = 0; i < actual.length; i++) {
assertSame("Wrong instance at index '" + i + "'", expected[i], actual[i]);
assertThat(actual[i]).as("Wrong instance at index '" + i + "'").isSameAs(expected[i]);
}
assertEquals("Wrong number of items", expected.length, expected.length);
assertThat(expected.length).as("Wrong number of items").isEqualTo(expected.length);
}

View File

@@ -20,8 +20,7 @@ import javax.annotation.Priority;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Stephane Nicoll
@@ -31,38 +30,38 @@ public class OrderUtilsTests {
@Test
public void getSimpleOrder() {
assertEquals(Integer.valueOf(50), OrderUtils.getOrder(SimpleOrder.class, null));
assertEquals(Integer.valueOf(50), OrderUtils.getOrder(SimpleOrder.class, null));
assertThat(OrderUtils.getOrder(SimpleOrder.class, null)).isEqualTo(Integer.valueOf(50));
assertThat(OrderUtils.getOrder(SimpleOrder.class, null)).isEqualTo(Integer.valueOf(50));
}
@Test
public void getPriorityOrder() {
assertEquals(Integer.valueOf(55), OrderUtils.getOrder(SimplePriority.class, null));
assertEquals(Integer.valueOf(55), OrderUtils.getOrder(SimplePriority.class, null));
assertThat(OrderUtils.getOrder(SimplePriority.class, null)).isEqualTo(Integer.valueOf(55));
assertThat(OrderUtils.getOrder(SimplePriority.class, null)).isEqualTo(Integer.valueOf(55));
}
@Test
public void getOrderWithBoth() {
assertEquals(Integer.valueOf(50), OrderUtils.getOrder(OrderAndPriority.class, null));
assertEquals(Integer.valueOf(50), OrderUtils.getOrder(OrderAndPriority.class, null));
assertThat(OrderUtils.getOrder(OrderAndPriority.class, null)).isEqualTo(Integer.valueOf(50));
assertThat(OrderUtils.getOrder(OrderAndPriority.class, null)).isEqualTo(Integer.valueOf(50));
}
@Test
public void getDefaultOrder() {
assertEquals(33, OrderUtils.getOrder(NoOrder.class, 33));
assertEquals(33, OrderUtils.getOrder(NoOrder.class, 33));
assertThat(OrderUtils.getOrder(NoOrder.class, 33)).isEqualTo(33);
assertThat(OrderUtils.getOrder(NoOrder.class, 33)).isEqualTo(33);
}
@Test
public void getPriorityValueNoAnnotation() {
assertNull(OrderUtils.getPriority(SimpleOrder.class));
assertNull(OrderUtils.getPriority(SimpleOrder.class));
assertThat(OrderUtils.getPriority(SimpleOrder.class)).isNull();
assertThat(OrderUtils.getPriority(SimpleOrder.class)).isNull();
}
@Test
public void getPriorityValue() {
assertEquals(Integer.valueOf(55), OrderUtils.getPriority(OrderAndPriority.class));
assertEquals(Integer.valueOf(55), OrderUtils.getPriority(OrderAndPriority.class));
assertThat(OrderUtils.getPriority(OrderAndPriority.class)).isEqualTo(Integer.valueOf(55));
assertThat(OrderUtils.getPriority(OrderAndPriority.class)).isEqualTo(Integer.valueOf(55));
}

View File

@@ -23,10 +23,8 @@ import org.junit.Test;
import org.springframework.core.MethodParameter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
/**
* @author Juergen Hoeller
@@ -54,50 +52,50 @@ public class SynthesizingMethodParameterTests {
@Test
public void testEquals() throws NoSuchMethodException {
assertEquals(stringParameter, stringParameter);
assertEquals(longParameter, longParameter);
assertEquals(intReturnType, intReturnType);
assertThat(stringParameter).isEqualTo(stringParameter);
assertThat(longParameter).isEqualTo(longParameter);
assertThat(intReturnType).isEqualTo(intReturnType);
assertFalse(stringParameter.equals(longParameter));
assertFalse(stringParameter.equals(intReturnType));
assertFalse(longParameter.equals(stringParameter));
assertFalse(longParameter.equals(intReturnType));
assertFalse(intReturnType.equals(stringParameter));
assertFalse(intReturnType.equals(longParameter));
assertThat(stringParameter.equals(longParameter)).isFalse();
assertThat(stringParameter.equals(intReturnType)).isFalse();
assertThat(longParameter.equals(stringParameter)).isFalse();
assertThat(longParameter.equals(intReturnType)).isFalse();
assertThat(intReturnType.equals(stringParameter)).isFalse();
assertThat(intReturnType.equals(longParameter)).isFalse();
Method method = getClass().getMethod("method", String.class, Long.TYPE);
MethodParameter methodParameter = new SynthesizingMethodParameter(method, 0);
assertEquals(stringParameter, methodParameter);
assertEquals(methodParameter, stringParameter);
assertNotEquals(longParameter, methodParameter);
assertNotEquals(methodParameter, longParameter);
assertThat(methodParameter).isEqualTo(stringParameter);
assertThat(stringParameter).isEqualTo(methodParameter);
assertThat(methodParameter).isNotEqualTo(longParameter);
assertThat(longParameter).isNotEqualTo(methodParameter);
methodParameter = new MethodParameter(method, 0);
assertEquals(stringParameter, methodParameter);
assertEquals(methodParameter, stringParameter);
assertNotEquals(longParameter, methodParameter);
assertNotEquals(methodParameter, longParameter);
assertThat(methodParameter).isEqualTo(stringParameter);
assertThat(stringParameter).isEqualTo(methodParameter);
assertThat(methodParameter).isNotEqualTo(longParameter);
assertThat(longParameter).isNotEqualTo(methodParameter);
}
@Test
public void testHashCode() throws NoSuchMethodException {
assertEquals(stringParameter.hashCode(), stringParameter.hashCode());
assertEquals(longParameter.hashCode(), longParameter.hashCode());
assertEquals(intReturnType.hashCode(), intReturnType.hashCode());
assertThat(stringParameter.hashCode()).isEqualTo(stringParameter.hashCode());
assertThat(longParameter.hashCode()).isEqualTo(longParameter.hashCode());
assertThat(intReturnType.hashCode()).isEqualTo(intReturnType.hashCode());
Method method = getClass().getMethod("method", String.class, Long.TYPE);
SynthesizingMethodParameter methodParameter = new SynthesizingMethodParameter(method, 0);
assertEquals(stringParameter.hashCode(), methodParameter.hashCode());
assertNotEquals(longParameter.hashCode(), methodParameter.hashCode());
assertThat(methodParameter.hashCode()).isEqualTo(stringParameter.hashCode());
assertThat(methodParameter.hashCode()).isNotEqualTo((long) longParameter.hashCode());
}
@Test
public void testFactoryMethods() {
assertEquals(stringParameter, SynthesizingMethodParameter.forExecutable(method, 0));
assertEquals(longParameter, SynthesizingMethodParameter.forExecutable(method, 1));
assertThat(SynthesizingMethodParameter.forExecutable(method, 0)).isEqualTo(stringParameter);
assertThat(SynthesizingMethodParameter.forExecutable(method, 1)).isEqualTo(longParameter);
assertEquals(stringParameter, SynthesizingMethodParameter.forParameter(method.getParameters()[0]));
assertEquals(longParameter, SynthesizingMethodParameter.forParameter(method.getParameters()[1]));
assertThat(SynthesizingMethodParameter.forParameter(method.getParameters()[0])).isEqualTo(stringParameter);
assertThat(SynthesizingMethodParameter.forParameter(method.getParameters()[1])).isEqualTo(longParameter);
}
@Test

View File

@@ -33,8 +33,7 @@ import org.springframework.util.Assert;
import org.springframework.util.MimeType;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.core.io.buffer.DataBufferUtils.release;
/**
@@ -150,7 +149,6 @@ public abstract class AbstractEncoderTestCase<E extends Encoder<?>>
* @param hints the hints used for decoding. May be {@code null}.
* @param <T> the output type
*/
@SuppressWarnings("unchecked")
protected <T> void testEncode(Publisher<? extends T> input, ResolvableType inputType,
Consumer<StepVerifier.FirstStep<DataBuffer>> stepConsumer,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
@@ -241,7 +239,7 @@ public abstract class AbstractEncoderTestCase<E extends Encoder<?>>
byte[] resultBytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(resultBytes);
release(dataBuffer);
assertArrayEquals(expected, resultBytes);
assertThat(resultBytes).isEqualTo(expected);
};
}
@@ -256,7 +254,7 @@ public abstract class AbstractEncoderTestCase<E extends Encoder<?>>
dataBuffer.read(resultBytes);
release(dataBuffer);
String actual = new String(resultBytes, UTF_8);
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
};
}

View File

@@ -26,9 +26,7 @@ import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.util.MimeTypeUtils;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Arjen Poutsma
@@ -47,12 +45,12 @@ public class ByteArrayDecoderTests extends AbstractDecoderTestCase<ByteArrayDeco
@Override
@Test
public void canDecode() {
assertTrue(this.decoder.canDecode(ResolvableType.forClass(byte[].class),
MimeTypeUtils.TEXT_PLAIN));
assertFalse(this.decoder.canDecode(ResolvableType.forClass(Integer.class),
MimeTypeUtils.TEXT_PLAIN));
assertTrue(this.decoder.canDecode(ResolvableType.forClass(byte[].class),
MimeTypeUtils.APPLICATION_JSON));
assertThat(this.decoder.canDecode(ResolvableType.forClass(byte[].class),
MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.decoder.canDecode(ResolvableType.forClass(Integer.class),
MimeTypeUtils.TEXT_PLAIN)).isFalse();
assertThat(this.decoder.canDecode(ResolvableType.forClass(byte[].class),
MimeTypeUtils.APPLICATION_JSON)).isTrue();
}
@Override
@@ -86,7 +84,7 @@ public class ByteArrayDecoderTests extends AbstractDecoderTestCase<ByteArrayDeco
}
private Consumer<byte[]> expectBytes(byte[] expected) {
return bytes -> assertArrayEquals(expected, bytes);
return bytes -> assertThat(bytes).isEqualTo(expected);
}
}

View File

@@ -24,8 +24,7 @@ import reactor.core.publisher.Flux;
import org.springframework.core.ResolvableType;
import org.springframework.util.MimeTypeUtils;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Arjen Poutsma
@@ -44,15 +43,15 @@ public class ByteArrayEncoderTests extends AbstractEncoderTestCase<ByteArrayEnco
@Override
@Test
public void canEncode() {
assertTrue(this.encoder.canEncode(ResolvableType.forClass(byte[].class),
MimeTypeUtils.TEXT_PLAIN));
assertFalse(this.encoder.canEncode(ResolvableType.forClass(Integer.class),
MimeTypeUtils.TEXT_PLAIN));
assertTrue(this.encoder.canEncode(ResolvableType.forClass(byte[].class),
MimeTypeUtils.APPLICATION_JSON));
assertThat(this.encoder.canEncode(ResolvableType.forClass(byte[].class),
MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.encoder.canEncode(ResolvableType.forClass(Integer.class),
MimeTypeUtils.TEXT_PLAIN)).isFalse();
assertThat(this.encoder.canEncode(ResolvableType.forClass(byte[].class),
MimeTypeUtils.APPLICATION_JSON)).isTrue();
// SPR-15464
assertFalse(this.encoder.canEncode(ResolvableType.NONE, null));
assertThat(this.encoder.canEncode(ResolvableType.NONE, null)).isFalse();
}
@Override

View File

@@ -27,9 +27,7 @@ import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.util.MimeTypeUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Sebastien Deleuze
@@ -48,12 +46,12 @@ public class ByteBufferDecoderTests extends AbstractDecoderTestCase<ByteBufferDe
@Override
@Test
public void canDecode() {
assertTrue(this.decoder.canDecode(ResolvableType.forClass(ByteBuffer.class),
MimeTypeUtils.TEXT_PLAIN));
assertFalse(this.decoder.canDecode(ResolvableType.forClass(Integer.class),
MimeTypeUtils.TEXT_PLAIN));
assertTrue(this.decoder.canDecode(ResolvableType.forClass(ByteBuffer.class),
MimeTypeUtils.APPLICATION_JSON));
assertThat(this.decoder.canDecode(ResolvableType.forClass(ByteBuffer.class),
MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.decoder.canDecode(ResolvableType.forClass(Integer.class),
MimeTypeUtils.TEXT_PLAIN)).isFalse();
assertThat(this.decoder.canDecode(ResolvableType.forClass(ByteBuffer.class),
MimeTypeUtils.APPLICATION_JSON)).isTrue();
}
@Override
@@ -87,7 +85,7 @@ public class ByteBufferDecoderTests extends AbstractDecoderTestCase<ByteBufferDe
}
private Consumer<ByteBuffer> expectByteBuffer(ByteBuffer expected) {
return actual -> assertEquals(expected, actual);
return actual -> assertThat(actual).isEqualTo(expected);
}
}

View File

@@ -25,8 +25,7 @@ import reactor.core.publisher.Flux;
import org.springframework.core.ResolvableType;
import org.springframework.util.MimeTypeUtils;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Sebastien Deleuze
@@ -44,15 +43,15 @@ public class ByteBufferEncoderTests extends AbstractEncoderTestCase<ByteBufferEn
@Override
@Test
public void canEncode() {
assertTrue(this.encoder.canEncode(ResolvableType.forClass(ByteBuffer.class),
MimeTypeUtils.TEXT_PLAIN));
assertFalse(this.encoder.canEncode(ResolvableType.forClass(Integer.class),
MimeTypeUtils.TEXT_PLAIN));
assertTrue(this.encoder.canEncode(ResolvableType.forClass(ByteBuffer.class),
MimeTypeUtils.APPLICATION_JSON));
assertThat(this.encoder.canEncode(ResolvableType.forClass(ByteBuffer.class),
MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.encoder.canEncode(ResolvableType.forClass(Integer.class),
MimeTypeUtils.TEXT_PLAIN)).isFalse();
assertThat(this.encoder.canEncode(ResolvableType.forClass(ByteBuffer.class),
MimeTypeUtils.APPLICATION_JSON)).isTrue();
// SPR-15464
assertFalse(this.encoder.canEncode(ResolvableType.NONE, null));
assertThat(this.encoder.canEncode(ResolvableType.NONE, null)).isFalse();
}
@Override

View File

@@ -29,8 +29,7 @@ import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.charset.StandardCharsets.UTF_16;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Sebastien Deleuze
@@ -49,19 +48,19 @@ public class CharSequenceEncoderTests
@Override
public void canEncode() throws Exception {
assertTrue(this.encoder.canEncode(ResolvableType.forClass(String.class),
MimeTypeUtils.TEXT_PLAIN));
assertTrue(this.encoder.canEncode(ResolvableType.forClass(StringBuilder.class),
MimeTypeUtils.TEXT_PLAIN));
assertTrue(this.encoder.canEncode(ResolvableType.forClass(StringBuffer.class),
MimeTypeUtils.TEXT_PLAIN));
assertFalse(this.encoder.canEncode(ResolvableType.forClass(Integer.class),
MimeTypeUtils.TEXT_PLAIN));
assertFalse(this.encoder.canEncode(ResolvableType.forClass(String.class),
MimeTypeUtils.APPLICATION_JSON));
assertThat(this.encoder.canEncode(ResolvableType.forClass(String.class),
MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.encoder.canEncode(ResolvableType.forClass(StringBuilder.class),
MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.encoder.canEncode(ResolvableType.forClass(StringBuffer.class),
MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.encoder.canEncode(ResolvableType.forClass(Integer.class),
MimeTypeUtils.TEXT_PLAIN)).isFalse();
assertThat(this.encoder.canEncode(ResolvableType.forClass(String.class),
MimeTypeUtils.APPLICATION_JSON)).isFalse();
// SPR-15464
assertFalse(this.encoder.canEncode(ResolvableType.NONE, null));
assertThat(this.encoder.canEncode(ResolvableType.NONE, null)).isFalse();
}
@Override
@@ -81,8 +80,7 @@ public class CharSequenceEncoderTests
.forEach(charset -> {
int capacity = this.encoder.calculateCapacity(sequence, charset);
int length = sequence.length();
assertTrue(String.format("%s has capacity %d; length %d", charset, capacity, length),
capacity >= length);
assertThat(capacity >= length).as(String.format("%s has capacity %d; length %d", charset, capacity, length)).isTrue();
});
}

View File

@@ -27,9 +27,7 @@ import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.util.MimeTypeUtils;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Sebastien Deleuze
@@ -48,12 +46,12 @@ public class DataBufferDecoderTests extends AbstractDecoderTestCase<DataBufferDe
@Override
@Test
public void canDecode() {
assertTrue(this.decoder.canDecode(ResolvableType.forClass(DataBuffer.class),
MimeTypeUtils.TEXT_PLAIN));
assertFalse(this.decoder.canDecode(ResolvableType.forClass(Integer.class),
MimeTypeUtils.TEXT_PLAIN));
assertTrue(this.decoder.canDecode(ResolvableType.forClass(DataBuffer.class),
MimeTypeUtils.APPLICATION_JSON));
assertThat(this.decoder.canDecode(ResolvableType.forClass(DataBuffer.class),
MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.decoder.canDecode(ResolvableType.forClass(Integer.class),
MimeTypeUtils.TEXT_PLAIN)).isFalse();
assertThat(this.decoder.canDecode(ResolvableType.forClass(DataBuffer.class),
MimeTypeUtils.APPLICATION_JSON)).isTrue();
}
@Override
@@ -87,7 +85,7 @@ public class DataBufferDecoderTests extends AbstractDecoderTestCase<DataBufferDe
return actual -> {
byte[] actualBytes = new byte[actual.readableByteCount()];
actual.read(actualBytes);
assertArrayEquals(expected, actualBytes);
assertThat(actualBytes).isEqualTo(expected);
DataBufferUtils.release(actual);
};

View File

@@ -26,8 +26,7 @@ import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.util.MimeTypeUtils;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Sebastien Deleuze
@@ -46,15 +45,15 @@ public class DataBufferEncoderTests extends AbstractEncoderTestCase<DataBufferEn
@Override
@Test
public void canEncode() {
assertTrue(this.encoder.canEncode(ResolvableType.forClass(DataBuffer.class),
MimeTypeUtils.TEXT_PLAIN));
assertFalse(this.encoder.canEncode(ResolvableType.forClass(Integer.class),
MimeTypeUtils.TEXT_PLAIN));
assertTrue(this.encoder.canEncode(ResolvableType.forClass(DataBuffer.class),
MimeTypeUtils.APPLICATION_JSON));
assertThat(this.encoder.canEncode(ResolvableType.forClass(DataBuffer.class),
MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.encoder.canEncode(ResolvableType.forClass(Integer.class),
MimeTypeUtils.TEXT_PLAIN)).isFalse();
assertThat(this.encoder.canEncode(ResolvableType.forClass(DataBuffer.class),
MimeTypeUtils.APPLICATION_JSON)).isTrue();
// SPR-15464
assertFalse(this.encoder.canEncode(ResolvableType.NONE, null));
assertThat(this.encoder.canEncode(ResolvableType.NONE, null)).isFalse();
}
@Override

View File

@@ -31,9 +31,7 @@ import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.StreamUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.core.ResolvableType.forClass;
/**
@@ -53,11 +51,11 @@ public class ResourceDecoderTests extends AbstractDecoderTestCase<ResourceDecode
@Override
@Test
public void canDecode() {
assertTrue(this.decoder.canDecode(forClass(InputStreamResource.class), MimeTypeUtils.TEXT_PLAIN));
assertTrue(this.decoder.canDecode(forClass(ByteArrayResource.class), MimeTypeUtils.TEXT_PLAIN));
assertTrue(this.decoder.canDecode(forClass(Resource.class), MimeTypeUtils.TEXT_PLAIN));
assertTrue(this.decoder.canDecode(forClass(InputStreamResource.class), MimeTypeUtils.APPLICATION_JSON));
assertFalse(this.decoder.canDecode(forClass(Object.class), MimeTypeUtils.APPLICATION_JSON));
assertThat(this.decoder.canDecode(forClass(InputStreamResource.class), MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.decoder.canDecode(forClass(ByteArrayResource.class), MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.decoder.canDecode(forClass(Resource.class), MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.decoder.canDecode(forClass(InputStreamResource.class), MimeTypeUtils.APPLICATION_JSON)).isTrue();
assertThat(this.decoder.canDecode(forClass(Object.class), MimeTypeUtils.APPLICATION_JSON)).isFalse();
}
@@ -70,7 +68,7 @@ public class ResourceDecoderTests extends AbstractDecoderTestCase<ResourceDecode
.consumeNextWith(resource -> {
try {
byte[] bytes = StreamUtils.copyToByteArray(resource.getInputStream());
assertEquals("foobar", new String(bytes));
assertThat(new String(bytes)).isEqualTo("foobar");
}
catch (IOException ex) {
throw new AssertionError(ex.getMessage(), ex);
@@ -92,8 +90,8 @@ public class ResourceDecoderTests extends AbstractDecoderTestCase<ResourceDecode
Resource resource = (Resource) value;
try {
byte[] bytes = StreamUtils.copyToByteArray(resource.getInputStream());
assertEquals("foobar", new String(bytes));
assertEquals("testFile", resource.getFilename());
assertThat(new String(bytes)).isEqualTo("foobar");
assertThat(resource.getFilename()).isEqualTo("testFile");
}
catch (IOException ex) {
throw new AssertionError(ex.getMessage(), ex);

View File

@@ -33,8 +33,7 @@ import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Arjen Poutsma
@@ -51,17 +50,17 @@ public class ResourceEncoderTests extends AbstractEncoderTestCase<ResourceEncode
@Override
@Test
public void canEncode() {
assertTrue(this.encoder.canEncode(ResolvableType.forClass(InputStreamResource.class),
MimeTypeUtils.TEXT_PLAIN));
assertTrue(this.encoder.canEncode(ResolvableType.forClass(ByteArrayResource.class),
MimeTypeUtils.TEXT_PLAIN));
assertTrue(this.encoder.canEncode(ResolvableType.forClass(Resource.class),
MimeTypeUtils.TEXT_PLAIN));
assertTrue(this.encoder.canEncode(ResolvableType.forClass(InputStreamResource.class),
MimeTypeUtils.APPLICATION_JSON));
assertThat(this.encoder.canEncode(ResolvableType.forClass(InputStreamResource.class),
MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.encoder.canEncode(ResolvableType.forClass(ByteArrayResource.class),
MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.encoder.canEncode(ResolvableType.forClass(Resource.class),
MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.encoder.canEncode(ResolvableType.forClass(InputStreamResource.class),
MimeTypeUtils.APPLICATION_JSON)).isTrue();
// SPR-15464
assertFalse(this.encoder.canEncode(ResolvableType.NONE, null));
assertThat(this.encoder.canEncode(ResolvableType.NONE, null)).isFalse();
}
@Override

View File

@@ -39,9 +39,7 @@ import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test cases for {@link ResourceRegionEncoder} class.
@@ -64,14 +62,14 @@ public class ResourceRegionEncoderTests {
ResolvableType resourceRegion = ResolvableType.forClass(ResourceRegion.class);
MimeType allMimeType = MimeType.valueOf("*/*");
assertFalse(this.encoder.canEncode(ResolvableType.forClass(Resource.class),
MimeTypeUtils.APPLICATION_OCTET_STREAM));
assertFalse(this.encoder.canEncode(ResolvableType.forClass(Resource.class), allMimeType));
assertTrue(this.encoder.canEncode(resourceRegion, MimeTypeUtils.APPLICATION_OCTET_STREAM));
assertTrue(this.encoder.canEncode(resourceRegion, allMimeType));
assertThat(this.encoder.canEncode(ResolvableType.forClass(Resource.class),
MimeTypeUtils.APPLICATION_OCTET_STREAM)).isFalse();
assertThat(this.encoder.canEncode(ResolvableType.forClass(Resource.class), allMimeType)).isFalse();
assertThat(this.encoder.canEncode(resourceRegion, MimeTypeUtils.APPLICATION_OCTET_STREAM)).isTrue();
assertThat(this.encoder.canEncode(resourceRegion, allMimeType)).isTrue();
// SPR-15464
assertFalse(this.encoder.canEncode(ResolvableType.NONE, null));
assertThat(this.encoder.canEncode(ResolvableType.NONE, null)).isFalse();
}
@Test
@@ -195,7 +193,7 @@ public class ResourceRegionEncoderTests {
return dataBuffer -> {
String value = DataBufferTestUtils.dumpString(dataBuffer, UTF_8);
DataBufferUtils.release(dataBuffer);
assertEquals(expected, value);
assertThat(value).isEqualTo(expected);
};
}

View File

@@ -34,8 +34,7 @@ import org.springframework.util.MimeTypeUtils;
import static java.nio.charset.StandardCharsets.UTF_16BE;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link StringDecoder}.
@@ -57,12 +56,12 @@ public class StringDecoderTests extends AbstractDecoderTestCase<StringDecoder> {
@Override
@Test
public void canDecode() {
assertTrue(this.decoder.canDecode(TYPE, MimeTypeUtils.TEXT_PLAIN));
assertTrue(this.decoder.canDecode(TYPE, MimeTypeUtils.TEXT_HTML));
assertTrue(this.decoder.canDecode(TYPE, MimeTypeUtils.APPLICATION_JSON));
assertTrue(this.decoder.canDecode(TYPE, MimeTypeUtils.parseMimeType("text/plain;charset=utf-8")));
assertFalse(this.decoder.canDecode(ResolvableType.forClass(Integer.class), MimeTypeUtils.TEXT_PLAIN));
assertFalse(this.decoder.canDecode(ResolvableType.forClass(Object.class), MimeTypeUtils.APPLICATION_JSON));
assertThat(this.decoder.canDecode(TYPE, MimeTypeUtils.TEXT_PLAIN)).isTrue();
assertThat(this.decoder.canDecode(TYPE, MimeTypeUtils.TEXT_HTML)).isTrue();
assertThat(this.decoder.canDecode(TYPE, MimeTypeUtils.APPLICATION_JSON)).isTrue();
assertThat(this.decoder.canDecode(TYPE, MimeTypeUtils.parseMimeType("text/plain;charset=utf-8"))).isTrue();
assertThat(this.decoder.canDecode(ResolvableType.forClass(Integer.class), MimeTypeUtils.TEXT_PLAIN)).isFalse();
assertThat(this.decoder.canDecode(ResolvableType.forClass(Object.class), MimeTypeUtils.APPLICATION_JSON)).isFalse();
}
@Override

View File

@@ -44,12 +44,6 @@ import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Tests for {@link TypeDescriptor}.
@@ -66,119 +60,119 @@ public class TypeDescriptorTests {
@Test
public void parameterPrimitive() throws Exception {
TypeDescriptor desc = new TypeDescriptor(new MethodParameter(getClass().getMethod("testParameterPrimitive", int.class), 0));
assertEquals(int.class, desc.getType());
assertEquals(Integer.class, desc.getObjectType());
assertEquals("int", desc.getName());
assertEquals("int", desc.toString());
assertTrue(desc.isPrimitive());
assertEquals(0, desc.getAnnotations().length);
assertFalse(desc.isCollection());
assertFalse(desc.isMap());
assertThat(desc.getType()).isEqualTo(int.class);
assertThat(desc.getObjectType()).isEqualTo(Integer.class);
assertThat(desc.getName()).isEqualTo("int");
assertThat(desc.toString()).isEqualTo("int");
assertThat(desc.isPrimitive()).isTrue();
assertThat(desc.getAnnotations().length).isEqualTo(0);
assertThat(desc.isCollection()).isFalse();
assertThat(desc.isMap()).isFalse();
}
@Test
public void parameterScalar() throws Exception {
TypeDescriptor desc = new TypeDescriptor(new MethodParameter(getClass().getMethod("testParameterScalar", String.class), 0));
assertEquals(String.class, desc.getType());
assertEquals(String.class, desc.getObjectType());
assertEquals("java.lang.String", desc.getName());
assertEquals("java.lang.String", desc.toString());
assertTrue(!desc.isPrimitive());
assertEquals(0, desc.getAnnotations().length);
assertFalse(desc.isCollection());
assertFalse(desc.isArray());
assertFalse(desc.isMap());
assertThat(desc.getType()).isEqualTo(String.class);
assertThat(desc.getObjectType()).isEqualTo(String.class);
assertThat(desc.getName()).isEqualTo("java.lang.String");
assertThat(desc.toString()).isEqualTo("java.lang.String");
assertThat(!desc.isPrimitive()).isTrue();
assertThat(desc.getAnnotations().length).isEqualTo(0);
assertThat(desc.isCollection()).isFalse();
assertThat(desc.isArray()).isFalse();
assertThat(desc.isMap()).isFalse();
}
@Test
public void parameterList() throws Exception {
MethodParameter methodParameter = new MethodParameter(getClass().getMethod("testParameterList", List.class), 0);
TypeDescriptor desc = new TypeDescriptor(methodParameter);
assertEquals(List.class, desc.getType());
assertEquals(List.class, desc.getObjectType());
assertEquals("java.util.List", desc.getName());
assertEquals("java.util.List<java.util.List<java.util.Map<java.lang.Integer, java.lang.Enum<?>>>>", desc.toString());
assertTrue(!desc.isPrimitive());
assertEquals(0, desc.getAnnotations().length);
assertTrue(desc.isCollection());
assertFalse(desc.isArray());
assertEquals(List.class, desc.getElementTypeDescriptor().getType());
assertEquals(TypeDescriptor.nested(methodParameter, 1), desc.getElementTypeDescriptor());
assertEquals(TypeDescriptor.nested(methodParameter, 2), desc.getElementTypeDescriptor().getElementTypeDescriptor());
assertEquals(TypeDescriptor.nested(methodParameter, 3), desc.getElementTypeDescriptor().getElementTypeDescriptor().getMapValueTypeDescriptor());
assertEquals(Integer.class, desc.getElementTypeDescriptor().getElementTypeDescriptor().getMapKeyTypeDescriptor().getType());
assertEquals(Enum.class, desc.getElementTypeDescriptor().getElementTypeDescriptor().getMapValueTypeDescriptor().getType());
assertFalse(desc.isMap());
assertThat(desc.getType()).isEqualTo(List.class);
assertThat(desc.getObjectType()).isEqualTo(List.class);
assertThat(desc.getName()).isEqualTo("java.util.List");
assertThat(desc.toString()).isEqualTo("java.util.List<java.util.List<java.util.Map<java.lang.Integer, java.lang.Enum<?>>>>");
assertThat(!desc.isPrimitive()).isTrue();
assertThat(desc.getAnnotations().length).isEqualTo(0);
assertThat(desc.isCollection()).isTrue();
assertThat(desc.isArray()).isFalse();
assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(List.class);
assertThat(desc.getElementTypeDescriptor()).isEqualTo(TypeDescriptor.nested(methodParameter, 1));
assertThat(desc.getElementTypeDescriptor().getElementTypeDescriptor()).isEqualTo(TypeDescriptor.nested(methodParameter, 2));
assertThat(desc.getElementTypeDescriptor().getElementTypeDescriptor().getMapValueTypeDescriptor()).isEqualTo(TypeDescriptor.nested(methodParameter, 3));
assertThat(desc.getElementTypeDescriptor().getElementTypeDescriptor().getMapKeyTypeDescriptor().getType()).isEqualTo(Integer.class);
assertThat(desc.getElementTypeDescriptor().getElementTypeDescriptor().getMapValueTypeDescriptor().getType()).isEqualTo(Enum.class);
assertThat(desc.isMap()).isFalse();
}
@Test
public void parameterListNoParamTypes() throws Exception {
MethodParameter methodParameter = new MethodParameter(getClass().getMethod("testParameterListNoParamTypes", List.class), 0);
TypeDescriptor desc = new TypeDescriptor(methodParameter);
assertEquals(List.class, desc.getType());
assertEquals(List.class, desc.getObjectType());
assertEquals("java.util.List", desc.getName());
assertEquals("java.util.List<?>", desc.toString());
assertTrue(!desc.isPrimitive());
assertEquals(0, desc.getAnnotations().length);
assertTrue(desc.isCollection());
assertFalse(desc.isArray());
assertNull(desc.getElementTypeDescriptor());
assertFalse(desc.isMap());
assertThat(desc.getType()).isEqualTo(List.class);
assertThat(desc.getObjectType()).isEqualTo(List.class);
assertThat(desc.getName()).isEqualTo("java.util.List");
assertThat(desc.toString()).isEqualTo("java.util.List<?>");
assertThat(!desc.isPrimitive()).isTrue();
assertThat(desc.getAnnotations().length).isEqualTo(0);
assertThat(desc.isCollection()).isTrue();
assertThat(desc.isArray()).isFalse();
assertThat((Object) desc.getElementTypeDescriptor()).isNull();
assertThat(desc.isMap()).isFalse();
}
@Test
public void parameterArray() throws Exception {
MethodParameter methodParameter = new MethodParameter(getClass().getMethod("testParameterArray", Integer[].class), 0);
TypeDescriptor desc = new TypeDescriptor(methodParameter);
assertEquals(Integer[].class, desc.getType());
assertEquals(Integer[].class, desc.getObjectType());
assertEquals("java.lang.Integer[]", desc.getName());
assertEquals("java.lang.Integer[]", desc.toString());
assertTrue(!desc.isPrimitive());
assertEquals(0, desc.getAnnotations().length);
assertFalse(desc.isCollection());
assertTrue(desc.isArray());
assertEquals(Integer.class, desc.getElementTypeDescriptor().getType());
assertEquals(TypeDescriptor.valueOf(Integer.class), desc.getElementTypeDescriptor());
assertFalse(desc.isMap());
assertThat(desc.getType()).isEqualTo(Integer[].class);
assertThat(desc.getObjectType()).isEqualTo(Integer[].class);
assertThat(desc.getName()).isEqualTo("java.lang.Integer[]");
assertThat(desc.toString()).isEqualTo("java.lang.Integer[]");
assertThat(!desc.isPrimitive()).isTrue();
assertThat(desc.getAnnotations().length).isEqualTo(0);
assertThat(desc.isCollection()).isFalse();
assertThat(desc.isArray()).isTrue();
assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
assertThat(desc.getElementTypeDescriptor()).isEqualTo(TypeDescriptor.valueOf(Integer.class));
assertThat(desc.isMap()).isFalse();
}
@Test
public void parameterMap() throws Exception {
MethodParameter methodParameter = new MethodParameter(getClass().getMethod("testParameterMap", Map.class), 0);
TypeDescriptor desc = new TypeDescriptor(methodParameter);
assertEquals(Map.class, desc.getType());
assertEquals(Map.class, desc.getObjectType());
assertEquals("java.util.Map", desc.getName());
assertEquals("java.util.Map<java.lang.Integer, java.util.List<java.lang.String>>", desc.toString());
assertTrue(!desc.isPrimitive());
assertEquals(0, desc.getAnnotations().length);
assertFalse(desc.isCollection());
assertFalse(desc.isArray());
assertTrue(desc.isMap());
assertEquals(TypeDescriptor.nested(methodParameter, 1), desc.getMapValueTypeDescriptor());
assertEquals(TypeDescriptor.nested(methodParameter, 2), desc.getMapValueTypeDescriptor().getElementTypeDescriptor());
assertEquals(Integer.class, desc.getMapKeyTypeDescriptor().getType());
assertEquals(List.class, desc.getMapValueTypeDescriptor().getType());
assertEquals(String.class, desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType());
assertThat(desc.getType()).isEqualTo(Map.class);
assertThat(desc.getObjectType()).isEqualTo(Map.class);
assertThat(desc.getName()).isEqualTo("java.util.Map");
assertThat(desc.toString()).isEqualTo("java.util.Map<java.lang.Integer, java.util.List<java.lang.String>>");
assertThat(!desc.isPrimitive()).isTrue();
assertThat(desc.getAnnotations().length).isEqualTo(0);
assertThat(desc.isCollection()).isFalse();
assertThat(desc.isArray()).isFalse();
assertThat(desc.isMap()).isTrue();
assertThat(desc.getMapValueTypeDescriptor()).isEqualTo(TypeDescriptor.nested(methodParameter, 1));
assertThat(desc.getMapValueTypeDescriptor().getElementTypeDescriptor()).isEqualTo(TypeDescriptor.nested(methodParameter, 2));
assertThat(desc.getMapKeyTypeDescriptor().getType()).isEqualTo(Integer.class);
assertThat(desc.getMapValueTypeDescriptor().getType()).isEqualTo(List.class);
assertThat(desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(String.class);
}
@Test
public void parameterAnnotated() throws Exception {
TypeDescriptor t1 = new TypeDescriptor(new MethodParameter(getClass().getMethod("testAnnotatedMethod", String.class), 0));
assertEquals(String.class, t1.getType());
assertEquals(1, t1.getAnnotations().length);
assertNotNull(t1.getAnnotation(ParameterAnnotation.class));
assertTrue(t1.hasAnnotation(ParameterAnnotation.class));
assertEquals(123, t1.getAnnotation(ParameterAnnotation.class).value());
assertThat(t1.getType()).isEqualTo(String.class);
assertThat(t1.getAnnotations().length).isEqualTo(1);
assertThat(t1.getAnnotation(ParameterAnnotation.class)).isNotNull();
assertThat(t1.hasAnnotation(ParameterAnnotation.class)).isTrue();
assertThat(t1.getAnnotation(ParameterAnnotation.class).value()).isEqualTo(123);
}
@Test
public void getAnnotationsReturnsClonedArray() throws Exception {
TypeDescriptor t = new TypeDescriptor(new MethodParameter(getClass().getMethod("testAnnotatedMethod", String.class), 0));
t.getAnnotations()[0] = null;
assertNotNull(t.getAnnotations()[0]);
assertThat(t.getAnnotations()[0]).isNotNull();
}
@Test
@@ -186,8 +180,8 @@ public class TypeDescriptorTests {
Property property = new Property(getClass(), getClass().getMethod("getComplexProperty"),
getClass().getMethod("setComplexProperty", Map.class));
TypeDescriptor desc = new TypeDescriptor(property);
assertEquals(String.class, desc.getMapKeyTypeDescriptor().getType());
assertEquals(Integer.class, desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getElementTypeDescriptor().getType());
assertThat(desc.getMapKeyTypeDescriptor().getType()).isEqualTo(String.class);
assertThat(desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
}
@Test
@@ -196,7 +190,7 @@ public class TypeDescriptorTests {
Property property = new Property(getClass(), genericBean.getClass().getMethod("getProperty"),
genericBean.getClass().getMethod("setProperty", Integer.class));
TypeDescriptor desc = new TypeDescriptor(property);
assertEquals(Integer.class, desc.getType());
assertThat(desc.getType()).isEqualTo(Integer.class);
}
@Test
@@ -205,7 +199,7 @@ public class TypeDescriptorTests {
Property property = new Property(getClass(), genericBean.getClass().getMethod("getProperty"),
genericBean.getClass().getMethod("setProperty", Number.class));
TypeDescriptor desc = new TypeDescriptor(property);
assertEquals(Integer.class, desc.getType());
assertThat(desc.getType()).isEqualTo(Integer.class);
}
@Test
@@ -214,8 +208,8 @@ public class TypeDescriptorTests {
Property property = new Property(getClass(), genericBean.getClass().getMethod("getListProperty"),
genericBean.getClass().getMethod("setListProperty", List.class));
TypeDescriptor desc = new TypeDescriptor(property);
assertEquals(List.class, desc.getType());
assertEquals(Integer.class, desc.getElementTypeDescriptor().getType());
assertThat(desc.getType()).isEqualTo(List.class);
assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
}
@Test
@@ -224,10 +218,10 @@ public class TypeDescriptorTests {
Property property = new Property(genericBean.getClass(), genericBean.getClass().getMethod("getListProperty"),
genericBean.getClass().getMethod("setListProperty", List.class));
TypeDescriptor desc = new TypeDescriptor(property);
assertEquals(List.class, desc.getType());
assertEquals(Integer.class, desc.getElementTypeDescriptor().getType());
assertNotNull(desc.getAnnotation(MethodAnnotation1.class));
assertTrue(desc.hasAnnotation(MethodAnnotation1.class));
assertThat(desc.getType()).isEqualTo(List.class);
assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
assertThat(desc.getAnnotation(MethodAnnotation1.class)).isNotNull();
assertThat(desc.hasAnnotation(MethodAnnotation1.class)).isTrue();
}
@Test
@@ -235,12 +229,12 @@ public class TypeDescriptorTests {
Property property = new Property(
getClass(), getClass().getMethod("getProperty"), getClass().getMethod("setProperty", Map.class));
TypeDescriptor desc = new TypeDescriptor(property);
assertEquals(Map.class, desc.getType());
assertEquals(Integer.class, desc.getMapKeyTypeDescriptor().getElementTypeDescriptor().getType());
assertEquals(Long.class, desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType());
assertNotNull(desc.getAnnotation(MethodAnnotation1.class));
assertNotNull(desc.getAnnotation(MethodAnnotation2.class));
assertNotNull(desc.getAnnotation(MethodAnnotation3.class));
assertThat(desc.getType()).isEqualTo(Map.class);
assertThat(desc.getMapKeyTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
assertThat(desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Long.class);
assertThat(desc.getAnnotation(MethodAnnotation1.class)).isNotNull();
assertThat(desc.getAnnotation(MethodAnnotation2.class)).isNotNull();
assertThat(desc.getAnnotation(MethodAnnotation3.class)).isNotNull();
}
@Test
@@ -260,160 +254,159 @@ public class TypeDescriptorTests {
private void assertAnnotationFoundOnMethod(Class<? extends Annotation> annotationType, String methodName) throws Exception {
TypeDescriptor typeDescriptor = new TypeDescriptor(new MethodParameter(getClass().getMethod(methodName), -1));
assertNotNull("Should have found @" + annotationType.getSimpleName() + " on " + methodName + ".",
typeDescriptor.getAnnotation(annotationType));
assertThat(typeDescriptor.getAnnotation(annotationType)).as("Should have found @" + annotationType.getSimpleName() + " on " + methodName + ".").isNotNull();
}
@Test
public void fieldScalar() throws Exception {
TypeDescriptor typeDescriptor = new TypeDescriptor(getClass().getField("fieldScalar"));
assertFalse(typeDescriptor.isPrimitive());
assertFalse(typeDescriptor.isArray());
assertFalse(typeDescriptor.isCollection());
assertFalse(typeDescriptor.isMap());
assertEquals(Integer.class, typeDescriptor.getType());
assertEquals(Integer.class, typeDescriptor.getObjectType());
assertThat(typeDescriptor.isPrimitive()).isFalse();
assertThat(typeDescriptor.isArray()).isFalse();
assertThat(typeDescriptor.isCollection()).isFalse();
assertThat(typeDescriptor.isMap()).isFalse();
assertThat(typeDescriptor.getType()).isEqualTo(Integer.class);
assertThat(typeDescriptor.getObjectType()).isEqualTo(Integer.class);
}
@Test
public void fieldList() throws Exception {
TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("listOfString"));
assertFalse(typeDescriptor.isArray());
assertEquals(List.class, typeDescriptor.getType());
assertEquals(String.class, typeDescriptor.getElementTypeDescriptor().getType());
assertEquals("java.util.List<java.lang.String>", typeDescriptor.toString());
assertThat(typeDescriptor.isArray()).isFalse();
assertThat(typeDescriptor.getType()).isEqualTo(List.class);
assertThat(typeDescriptor.getElementTypeDescriptor().getType()).isEqualTo(String.class);
assertThat(typeDescriptor.toString()).isEqualTo("java.util.List<java.lang.String>");
}
@Test
public void fieldListOfListOfString() throws Exception {
TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("listOfListOfString"));
assertFalse(typeDescriptor.isArray());
assertEquals(List.class, typeDescriptor.getType());
assertEquals(List.class, typeDescriptor.getElementTypeDescriptor().getType());
assertEquals(String.class, typeDescriptor.getElementTypeDescriptor().getElementTypeDescriptor().getType());
assertEquals("java.util.List<java.util.List<java.lang.String>>", typeDescriptor.toString());
assertThat(typeDescriptor.isArray()).isFalse();
assertThat(typeDescriptor.getType()).isEqualTo(List.class);
assertThat(typeDescriptor.getElementTypeDescriptor().getType()).isEqualTo(List.class);
assertThat(typeDescriptor.getElementTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(String.class);
assertThat(typeDescriptor.toString()).isEqualTo("java.util.List<java.util.List<java.lang.String>>");
}
@Test
public void fieldListOfListUnknown() throws Exception {
TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("listOfListOfUnknown"));
assertFalse(typeDescriptor.isArray());
assertEquals(List.class, typeDescriptor.getType());
assertEquals(List.class, typeDescriptor.getElementTypeDescriptor().getType());
assertNull(typeDescriptor.getElementTypeDescriptor().getElementTypeDescriptor());
assertEquals("java.util.List<java.util.List<?>>", typeDescriptor.toString());
assertThat(typeDescriptor.isArray()).isFalse();
assertThat(typeDescriptor.getType()).isEqualTo(List.class);
assertThat(typeDescriptor.getElementTypeDescriptor().getType()).isEqualTo(List.class);
assertThat(typeDescriptor.getElementTypeDescriptor().getElementTypeDescriptor()).isNull();
assertThat(typeDescriptor.toString()).isEqualTo("java.util.List<java.util.List<?>>");
}
@Test
public void fieldArray() throws Exception {
TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("intArray"));
assertTrue(typeDescriptor.isArray());
assertEquals(Integer.TYPE,typeDescriptor.getElementTypeDescriptor().getType());
assertEquals("int[]",typeDescriptor.toString());
assertThat(typeDescriptor.isArray()).isTrue();
assertThat(typeDescriptor.getElementTypeDescriptor().getType()).isEqualTo(Integer.TYPE);
assertThat(typeDescriptor.toString()).isEqualTo("int[]");
}
@Test
public void fieldComplexTypeDescriptor() throws Exception {
TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("arrayOfListOfString"));
assertTrue(typeDescriptor.isArray());
assertEquals(List.class,typeDescriptor.getElementTypeDescriptor().getType());
assertEquals(String.class, typeDescriptor.getElementTypeDescriptor().getElementTypeDescriptor().getType());
assertEquals("java.util.List<java.lang.String>[]",typeDescriptor.toString());
assertThat(typeDescriptor.isArray()).isTrue();
assertThat(typeDescriptor.getElementTypeDescriptor().getType()).isEqualTo(List.class);
assertThat(typeDescriptor.getElementTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(String.class);
assertThat(typeDescriptor.toString()).isEqualTo("java.util.List<java.lang.String>[]");
}
@Test
public void fieldComplexTypeDescriptor2() throws Exception {
TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("nestedMapField"));
assertTrue(typeDescriptor.isMap());
assertEquals(String.class,typeDescriptor.getMapKeyTypeDescriptor().getType());
assertEquals(List.class, typeDescriptor.getMapValueTypeDescriptor().getType());
assertEquals(Integer.class, typeDescriptor.getMapValueTypeDescriptor().getElementTypeDescriptor().getType());
assertEquals("java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>", typeDescriptor.toString());
assertThat(typeDescriptor.isMap()).isTrue();
assertThat(typeDescriptor.getMapKeyTypeDescriptor().getType()).isEqualTo(String.class);
assertThat(typeDescriptor.getMapValueTypeDescriptor().getType()).isEqualTo(List.class);
assertThat(typeDescriptor.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
assertThat(typeDescriptor.toString()).isEqualTo("java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>");
}
@Test
public void fieldMap() throws Exception {
TypeDescriptor desc = new TypeDescriptor(TypeDescriptorTests.class.getField("fieldMap"));
assertTrue(desc.isMap());
assertEquals(Integer.class, desc.getMapKeyTypeDescriptor().getElementTypeDescriptor().getType());
assertEquals(Long.class, desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType());
assertThat(desc.isMap()).isTrue();
assertThat(desc.getMapKeyTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
assertThat(desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Long.class);
}
@Test
public void fieldAnnotated() throws Exception {
TypeDescriptor typeDescriptor = new TypeDescriptor(getClass().getField("fieldAnnotated"));
assertEquals(1, typeDescriptor.getAnnotations().length);
assertNotNull(typeDescriptor.getAnnotation(FieldAnnotation.class));
assertThat(typeDescriptor.getAnnotations().length).isEqualTo(1);
assertThat(typeDescriptor.getAnnotation(FieldAnnotation.class)).isNotNull();
}
@Test
public void valueOfScalar() {
TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(Integer.class);
assertFalse(typeDescriptor.isPrimitive());
assertFalse(typeDescriptor.isArray());
assertFalse(typeDescriptor.isCollection());
assertFalse(typeDescriptor.isMap());
assertEquals(Integer.class, typeDescriptor.getType());
assertEquals(Integer.class, typeDescriptor.getObjectType());
assertThat(typeDescriptor.isPrimitive()).isFalse();
assertThat(typeDescriptor.isArray()).isFalse();
assertThat(typeDescriptor.isCollection()).isFalse();
assertThat(typeDescriptor.isMap()).isFalse();
assertThat(typeDescriptor.getType()).isEqualTo(Integer.class);
assertThat(typeDescriptor.getObjectType()).isEqualTo(Integer.class);
}
@Test
public void valueOfPrimitive() {
TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(int.class);
assertTrue(typeDescriptor.isPrimitive());
assertFalse(typeDescriptor.isArray());
assertFalse(typeDescriptor.isCollection());
assertFalse(typeDescriptor.isMap());
assertEquals(Integer.TYPE, typeDescriptor.getType());
assertEquals(Integer.class, typeDescriptor.getObjectType());
assertThat(typeDescriptor.isPrimitive()).isTrue();
assertThat(typeDescriptor.isArray()).isFalse();
assertThat(typeDescriptor.isCollection()).isFalse();
assertThat(typeDescriptor.isMap()).isFalse();
assertThat(typeDescriptor.getType()).isEqualTo(Integer.TYPE);
assertThat(typeDescriptor.getObjectType()).isEqualTo(Integer.class);
}
@Test
public void valueOfArray() throws Exception {
TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(int[].class);
assertTrue(typeDescriptor.isArray());
assertFalse(typeDescriptor.isCollection());
assertFalse(typeDescriptor.isMap());
assertEquals(Integer.TYPE, typeDescriptor.getElementTypeDescriptor().getType());
assertThat(typeDescriptor.isArray()).isTrue();
assertThat(typeDescriptor.isCollection()).isFalse();
assertThat(typeDescriptor.isMap()).isFalse();
assertThat(typeDescriptor.getElementTypeDescriptor().getType()).isEqualTo(Integer.TYPE);
}
@Test
public void valueOfCollection() throws Exception {
TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(Collection.class);
assertTrue(typeDescriptor.isCollection());
assertFalse(typeDescriptor.isArray());
assertFalse(typeDescriptor.isMap());
assertNull(typeDescriptor.getElementTypeDescriptor());
assertThat(typeDescriptor.isCollection()).isTrue();
assertThat(typeDescriptor.isArray()).isFalse();
assertThat(typeDescriptor.isMap()).isFalse();
assertThat((Object) typeDescriptor.getElementTypeDescriptor()).isNull();
}
@Test
public void forObject() {
TypeDescriptor desc = TypeDescriptor.forObject("3");
assertEquals(String.class, desc.getType());
assertThat(desc.getType()).isEqualTo(String.class);
}
@Test
public void forObjectNullTypeDescriptor() {
TypeDescriptor desc = TypeDescriptor.forObject(null);
assertNull(desc);
assertThat((Object) desc).isNull();
}
@Test
public void nestedMethodParameterType2Levels() throws Exception {
TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test2", List.class), 0), 2);
assertEquals(String.class, t1.getType());
assertThat(t1.getType()).isEqualTo(String.class);
}
@Test
public void nestedMethodParameterTypeMap() throws Exception {
TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test3", Map.class), 0), 1);
assertEquals(String.class, t1.getType());
assertThat(t1.getType()).isEqualTo(String.class);
}
@Test
public void nestedMethodParameterTypeMapTwoLevels() throws Exception {
TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test4", List.class), 0), 2);
assertEquals(String.class, t1.getType());
assertThat(t1.getType()).isEqualTo(String.class);
}
@Test
@@ -425,13 +418,13 @@ public class TypeDescriptorTests {
@Test
public void nestedTooManyLevels() throws Exception {
TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test4", List.class), 0), 3);
assertNull(t1);
assertThat((Object) t1).isNull();
}
@Test
public void nestedMethodParameterTypeNotNestable() throws Exception {
TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test5", String.class), 0), 2);
assertNull(t1);
assertThat((Object) t1).isNull();
}
@Test
@@ -443,89 +436,89 @@ public class TypeDescriptorTests {
@Test
public void nestedNotParameterized() throws Exception {
TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test6", List.class), 0), 1);
assertEquals(List.class,t1.getType());
assertEquals("java.util.List<?>", t1.toString());
assertThat(t1.getType()).isEqualTo(List.class);
assertThat(t1.toString()).isEqualTo("java.util.List<?>");
TypeDescriptor t2 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test6", List.class), 0), 2);
assertNull(t2);
assertThat((Object) t2).isNull();
}
@Test
public void nestedFieldTypeMapTwoLevels() throws Exception {
TypeDescriptor t1 = TypeDescriptor.nested(getClass().getField("test4"), 2);
assertEquals(String.class, t1.getType());
assertThat(t1.getType()).isEqualTo(String.class);
}
@Test
public void nestedPropertyTypeMapTwoLevels() throws Exception {
Property property = new Property(getClass(), getClass().getMethod("getTest4"), getClass().getMethod("setTest4", List.class));
TypeDescriptor t1 = TypeDescriptor.nested(property, 2);
assertEquals(String.class, t1.getType());
assertThat(t1.getType()).isEqualTo(String.class);
}
@Test
public void collection() {
TypeDescriptor desc = TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(Integer.class));
assertEquals(List.class, desc.getType());
assertEquals(List.class, desc.getObjectType());
assertEquals("java.util.List", desc.getName());
assertEquals("java.util.List<java.lang.Integer>", desc.toString());
assertTrue(!desc.isPrimitive());
assertEquals(0, desc.getAnnotations().length);
assertTrue(desc.isCollection());
assertFalse(desc.isArray());
assertEquals(Integer.class, desc.getElementTypeDescriptor().getType());
assertEquals(TypeDescriptor.valueOf(Integer.class), desc.getElementTypeDescriptor());
assertFalse(desc.isMap());
assertThat(desc.getType()).isEqualTo(List.class);
assertThat(desc.getObjectType()).isEqualTo(List.class);
assertThat(desc.getName()).isEqualTo("java.util.List");
assertThat(desc.toString()).isEqualTo("java.util.List<java.lang.Integer>");
assertThat(!desc.isPrimitive()).isTrue();
assertThat(desc.getAnnotations().length).isEqualTo(0);
assertThat(desc.isCollection()).isTrue();
assertThat(desc.isArray()).isFalse();
assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
assertThat(desc.getElementTypeDescriptor()).isEqualTo(TypeDescriptor.valueOf(Integer.class));
assertThat(desc.isMap()).isFalse();
}
@Test
public void collectionNested() {
TypeDescriptor desc = TypeDescriptor.collection(List.class, TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(Integer.class)));
assertEquals(List.class, desc.getType());
assertEquals(List.class, desc.getObjectType());
assertEquals("java.util.List", desc.getName());
assertEquals("java.util.List<java.util.List<java.lang.Integer>>", desc.toString());
assertTrue(!desc.isPrimitive());
assertEquals(0, desc.getAnnotations().length);
assertTrue(desc.isCollection());
assertFalse(desc.isArray());
assertEquals(List.class, desc.getElementTypeDescriptor().getType());
assertEquals(TypeDescriptor.valueOf(Integer.class), desc.getElementTypeDescriptor().getElementTypeDescriptor());
assertFalse(desc.isMap());
assertThat(desc.getType()).isEqualTo(List.class);
assertThat(desc.getObjectType()).isEqualTo(List.class);
assertThat(desc.getName()).isEqualTo("java.util.List");
assertThat(desc.toString()).isEqualTo("java.util.List<java.util.List<java.lang.Integer>>");
assertThat(!desc.isPrimitive()).isTrue();
assertThat(desc.getAnnotations().length).isEqualTo(0);
assertThat(desc.isCollection()).isTrue();
assertThat(desc.isArray()).isFalse();
assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(List.class);
assertThat(desc.getElementTypeDescriptor().getElementTypeDescriptor()).isEqualTo(TypeDescriptor.valueOf(Integer.class));
assertThat(desc.isMap()).isFalse();
}
@Test
public void map() {
TypeDescriptor desc = TypeDescriptor.map(Map.class, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class));
assertEquals(Map.class, desc.getType());
assertEquals(Map.class, desc.getObjectType());
assertEquals("java.util.Map", desc.getName());
assertEquals("java.util.Map<java.lang.String, java.lang.Integer>", desc.toString());
assertTrue(!desc.isPrimitive());
assertEquals(0, desc.getAnnotations().length);
assertFalse(desc.isCollection());
assertFalse(desc.isArray());
assertTrue(desc.isMap());
assertEquals(String.class, desc.getMapKeyTypeDescriptor().getType());
assertEquals(Integer.class, desc.getMapValueTypeDescriptor().getType());
assertThat(desc.getType()).isEqualTo(Map.class);
assertThat(desc.getObjectType()).isEqualTo(Map.class);
assertThat(desc.getName()).isEqualTo("java.util.Map");
assertThat(desc.toString()).isEqualTo("java.util.Map<java.lang.String, java.lang.Integer>");
assertThat(!desc.isPrimitive()).isTrue();
assertThat(desc.getAnnotations().length).isEqualTo(0);
assertThat(desc.isCollection()).isFalse();
assertThat(desc.isArray()).isFalse();
assertThat(desc.isMap()).isTrue();
assertThat(desc.getMapKeyTypeDescriptor().getType()).isEqualTo(String.class);
assertThat(desc.getMapValueTypeDescriptor().getType()).isEqualTo(Integer.class);
}
@Test
public void mapNested() {
TypeDescriptor desc = TypeDescriptor.map(Map.class, TypeDescriptor.valueOf(String.class),
TypeDescriptor.map(Map.class, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class)));
assertEquals(Map.class, desc.getType());
assertEquals(Map.class, desc.getObjectType());
assertEquals("java.util.Map", desc.getName());
assertEquals("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.lang.Integer>>", desc.toString());
assertTrue(!desc.isPrimitive());
assertEquals(0, desc.getAnnotations().length);
assertFalse(desc.isCollection());
assertFalse(desc.isArray());
assertTrue(desc.isMap());
assertEquals(String.class, desc.getMapKeyTypeDescriptor().getType());
assertEquals(String.class, desc.getMapValueTypeDescriptor().getMapKeyTypeDescriptor().getType());
assertEquals(Integer.class, desc.getMapValueTypeDescriptor().getMapValueTypeDescriptor().getType());
assertThat(desc.getType()).isEqualTo(Map.class);
assertThat(desc.getObjectType()).isEqualTo(Map.class);
assertThat(desc.getName()).isEqualTo("java.util.Map");
assertThat(desc.toString()).isEqualTo("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.lang.Integer>>");
assertThat(!desc.isPrimitive()).isTrue();
assertThat(desc.getAnnotations().length).isEqualTo(0);
assertThat(desc.isCollection()).isFalse();
assertThat(desc.isArray()).isFalse();
assertThat(desc.isMap()).isTrue();
assertThat(desc.getMapKeyTypeDescriptor().getType()).isEqualTo(String.class);
assertThat(desc.getMapValueTypeDescriptor().getMapKeyTypeDescriptor().getType()).isEqualTo(String.class);
assertThat(desc.getMapValueTypeDescriptor().getMapValueTypeDescriptor().getType()).isEqualTo(Integer.class);
}
@Test
@@ -533,7 +526,7 @@ public class TypeDescriptorTests {
TypeDescriptor desc = TypeDescriptor.valueOf(Number.class);
Integer value = Integer.valueOf(3);
desc = desc.narrow(value);
assertEquals(Integer.class, desc.getType());
assertThat(desc.getType()).isEqualTo(Integer.class);
}
@Test
@@ -541,17 +534,17 @@ public class TypeDescriptorTests {
TypeDescriptor desc = TypeDescriptor.valueOf(List.class);
Integer value = Integer.valueOf(3);
desc = desc.elementTypeDescriptor(value);
assertEquals(Integer.class, desc.getType());
assertThat(desc.getType()).isEqualTo(Integer.class);
}
@Test
public void elementTypePreserveContext() throws Exception {
TypeDescriptor desc = new TypeDescriptor(getClass().getField("listPreserveContext"));
assertEquals(Integer.class, desc.getElementTypeDescriptor().getElementTypeDescriptor().getType());
assertThat(desc.getElementTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
List<Integer> value = new ArrayList<>(3);
desc = desc.elementTypeDescriptor(value);
assertEquals(Integer.class, desc.getElementTypeDescriptor().getType());
assertNotNull(desc.getAnnotation(FieldAnnotation.class));
assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
assertThat(desc.getAnnotation(FieldAnnotation.class)).isNotNull();
}
@Test
@@ -559,17 +552,17 @@ public class TypeDescriptorTests {
TypeDescriptor desc = TypeDescriptor.valueOf(Map.class);
Integer value = Integer.valueOf(3);
desc = desc.getMapKeyTypeDescriptor(value);
assertEquals(Integer.class, desc.getType());
assertThat(desc.getType()).isEqualTo(Integer.class);
}
@Test
public void mapKeyTypePreserveContext() throws Exception {
TypeDescriptor desc = new TypeDescriptor(getClass().getField("mapPreserveContext"));
assertEquals(Integer.class, desc.getMapKeyTypeDescriptor().getElementTypeDescriptor().getType());
assertThat(desc.getMapKeyTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
List<Integer> value = new ArrayList<>(3);
desc = desc.getMapKeyTypeDescriptor(value);
assertEquals(Integer.class, desc.getElementTypeDescriptor().getType());
assertNotNull(desc.getAnnotation(FieldAnnotation.class));
assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
assertThat(desc.getAnnotation(FieldAnnotation.class)).isNotNull();
}
@Test
@@ -577,17 +570,17 @@ public class TypeDescriptorTests {
TypeDescriptor desc = TypeDescriptor.valueOf(Map.class);
Integer value = Integer.valueOf(3);
desc = desc.getMapValueTypeDescriptor(value);
assertEquals(Integer.class, desc.getType());
assertThat(desc.getType()).isEqualTo(Integer.class);
}
@Test
public void mapValueTypePreserveContext() throws Exception {
TypeDescriptor desc = new TypeDescriptor(getClass().getField("mapPreserveContext"));
assertEquals(Integer.class, desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType());
assertThat(desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
List<Integer> value = new ArrayList<>(3);
desc = desc.getMapValueTypeDescriptor(value);
assertEquals(Integer.class, desc.getElementTypeDescriptor().getType());
assertNotNull(desc.getAnnotation(FieldAnnotation.class));
assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
assertThat(desc.getAnnotation(FieldAnnotation.class)).isNotNull();
}
@Test
@@ -600,74 +593,73 @@ public class TypeDescriptorTests {
TypeDescriptor t6 = TypeDescriptor.valueOf(List.class);
TypeDescriptor t7 = TypeDescriptor.valueOf(Map.class);
TypeDescriptor t8 = TypeDescriptor.valueOf(Map.class);
assertEquals(t1, t2);
assertEquals(t3, t4);
assertEquals(t5, t6);
assertEquals(t7, t8);
assertThat(t2).isEqualTo(t1);
assertThat(t4).isEqualTo(t3);
assertThat(t6).isEqualTo(t5);
assertThat(t8).isEqualTo(t7);
TypeDescriptor t9 = new TypeDescriptor(getClass().getField("listField"));
TypeDescriptor t10 = new TypeDescriptor(getClass().getField("listField"));
assertEquals(t9, t10);
assertThat(t10).isEqualTo(t9);
TypeDescriptor t11 = new TypeDescriptor(getClass().getField("mapField"));
TypeDescriptor t12 = new TypeDescriptor(getClass().getField("mapField"));
assertEquals(t11, t12);
assertThat(t12).isEqualTo(t11);
MethodParameter testAnnotatedMethod = new MethodParameter(getClass().getMethod("testAnnotatedMethod", String.class), 0);
TypeDescriptor t13 = new TypeDescriptor(testAnnotatedMethod);
TypeDescriptor t14 = new TypeDescriptor(testAnnotatedMethod);
assertEquals(t13, t14);
assertThat(t14).isEqualTo(t13);
TypeDescriptor t15 = new TypeDescriptor(testAnnotatedMethod);
TypeDescriptor t16 = new TypeDescriptor(new MethodParameter(getClass().getMethod("testAnnotatedMethodDifferentAnnotationValue", String.class), 0));
assertNotEquals(t15, t16);
assertThat(t16).isNotEqualTo(t15);
TypeDescriptor t17 = new TypeDescriptor(testAnnotatedMethod);
TypeDescriptor t18 = new TypeDescriptor(new MethodParameter(getClass().getMethod("test5", String.class), 0));
assertNotEquals(t17, t18);
assertThat(t18).isNotEqualTo(t17);
}
@Test
public void isAssignableTypes() {
assertTrue(TypeDescriptor.valueOf(Integer.class).isAssignableTo(TypeDescriptor.valueOf(Number.class)));
assertFalse(TypeDescriptor.valueOf(Number.class).isAssignableTo(TypeDescriptor.valueOf(Integer.class)));
assertFalse(TypeDescriptor.valueOf(String.class).isAssignableTo(TypeDescriptor.valueOf(String[].class)));
assertThat(TypeDescriptor.valueOf(Integer.class).isAssignableTo(TypeDescriptor.valueOf(Number.class))).isTrue();
assertThat(TypeDescriptor.valueOf(Number.class).isAssignableTo(TypeDescriptor.valueOf(Integer.class))).isFalse();
assertThat(TypeDescriptor.valueOf(String.class).isAssignableTo(TypeDescriptor.valueOf(String[].class))).isFalse();
}
@Test
public void isAssignableElementTypes() throws Exception {
assertTrue(new TypeDescriptor(getClass().getField("listField")).isAssignableTo(new TypeDescriptor(getClass().getField("listField"))));
assertTrue(new TypeDescriptor(getClass().getField("notGenericList")).isAssignableTo(new TypeDescriptor(getClass().getField("listField"))));
assertTrue(new TypeDescriptor(getClass().getField("listField")).isAssignableTo(new TypeDescriptor(getClass().getField("notGenericList"))));
assertFalse(new TypeDescriptor(getClass().getField("isAssignableElementTypes")).isAssignableTo(new TypeDescriptor(getClass().getField("listField"))));
assertTrue(TypeDescriptor.valueOf(List.class).isAssignableTo(new TypeDescriptor(getClass().getField("listField"))));
assertThat(new TypeDescriptor(getClass().getField("listField")).isAssignableTo(new TypeDescriptor(getClass().getField("listField")))).isTrue();
assertThat(new TypeDescriptor(getClass().getField("notGenericList")).isAssignableTo(new TypeDescriptor(getClass().getField("listField")))).isTrue();
assertThat(new TypeDescriptor(getClass().getField("listField")).isAssignableTo(new TypeDescriptor(getClass().getField("notGenericList")))).isTrue();
assertThat(new TypeDescriptor(getClass().getField("isAssignableElementTypes")).isAssignableTo(new TypeDescriptor(getClass().getField("listField")))).isFalse();
assertThat(TypeDescriptor.valueOf(List.class).isAssignableTo(new TypeDescriptor(getClass().getField("listField")))).isTrue();
}
@Test
public void isAssignableMapKeyValueTypes() throws Exception {
assertTrue(new TypeDescriptor(getClass().getField("mapField")).isAssignableTo(new TypeDescriptor(getClass().getField("mapField"))));
assertTrue(new TypeDescriptor(getClass().getField("notGenericMap")).isAssignableTo(new TypeDescriptor(getClass().getField("mapField"))));
assertTrue(new TypeDescriptor(getClass().getField("mapField")).isAssignableTo(new TypeDescriptor(getClass().getField("notGenericMap"))));
assertFalse(new TypeDescriptor(getClass().getField("isAssignableMapKeyValueTypes")).isAssignableTo(new TypeDescriptor(getClass().getField("mapField"))));
assertTrue(TypeDescriptor.valueOf(Map.class).isAssignableTo(new TypeDescriptor(getClass().getField("mapField"))));
assertThat(new TypeDescriptor(getClass().getField("mapField")).isAssignableTo(new TypeDescriptor(getClass().getField("mapField")))).isTrue();
assertThat(new TypeDescriptor(getClass().getField("notGenericMap")).isAssignableTo(new TypeDescriptor(getClass().getField("mapField")))).isTrue();
assertThat(new TypeDescriptor(getClass().getField("mapField")).isAssignableTo(new TypeDescriptor(getClass().getField("notGenericMap")))).isTrue();
assertThat(new TypeDescriptor(getClass().getField("isAssignableMapKeyValueTypes")).isAssignableTo(new TypeDescriptor(getClass().getField("mapField")))).isFalse();
assertThat(TypeDescriptor.valueOf(Map.class).isAssignableTo(new TypeDescriptor(getClass().getField("mapField")))).isTrue();
}
@Test
public void multiValueMap() throws Exception {
TypeDescriptor td = new TypeDescriptor(getClass().getField("multiValueMap"));
assertTrue(td.isMap());
assertEquals(String.class, td.getMapKeyTypeDescriptor().getType());
assertEquals(List.class, td.getMapValueTypeDescriptor().getType());
assertEquals(Integer.class,
td.getMapValueTypeDescriptor().getElementTypeDescriptor().getType());
assertThat(td.isMap()).isTrue();
assertThat(td.getMapKeyTypeDescriptor().getType()).isEqualTo(String.class);
assertThat(td.getMapValueTypeDescriptor().getType()).isEqualTo(List.class);
assertThat(td.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
}
@Test
public void passDownGeneric() throws Exception {
TypeDescriptor td = new TypeDescriptor(getClass().getField("passDownGeneric"));
assertEquals(List.class, td.getElementTypeDescriptor().getType());
assertEquals(Set.class, td.getElementTypeDescriptor().getElementTypeDescriptor().getType());
assertEquals(Integer.class, td.getElementTypeDescriptor().getElementTypeDescriptor().getElementTypeDescriptor().getType());
assertThat(td.getElementTypeDescriptor().getType()).isEqualTo(List.class);
assertThat(td.getElementTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Set.class);
assertThat(td.getElementTypeDescriptor().getElementTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class);
}
@Test
@@ -676,7 +668,7 @@ public class TypeDescriptorTests {
getClass().getMethod("setProperty", Map.class));
TypeDescriptor typeDescriptor = new TypeDescriptor(property);
TypeDescriptor upCast = typeDescriptor.upcast(Object.class);
assertTrue(upCast.getAnnotation(MethodAnnotation1.class) != null);
assertThat(upCast.getAnnotation(MethodAnnotation1.class) != null).isTrue();
}
@Test
@@ -695,8 +687,8 @@ public class TypeDescriptorTests {
class CustomSet extends HashSet<String> {
}
assertEquals(TypeDescriptor.valueOf(CustomSet.class).getElementTypeDescriptor(), TypeDescriptor.valueOf(String.class));
assertEquals(TypeDescriptor.forObject(new CustomSet()).getElementTypeDescriptor(), TypeDescriptor.valueOf(String.class));
assertThat(TypeDescriptor.valueOf(String.class)).isEqualTo(TypeDescriptor.valueOf(CustomSet.class).getElementTypeDescriptor());
assertThat(TypeDescriptor.valueOf(String.class)).isEqualTo(TypeDescriptor.forObject(new CustomSet()).getElementTypeDescriptor());
}
@Test
@@ -705,10 +697,10 @@ public class TypeDescriptorTests {
class CustomMap extends HashMap<String, Integer> {
}
assertEquals(TypeDescriptor.valueOf(CustomMap.class).getMapKeyTypeDescriptor(), TypeDescriptor.valueOf(String.class));
assertEquals(TypeDescriptor.valueOf(CustomMap.class).getMapValueTypeDescriptor(), TypeDescriptor.valueOf(Integer.class));
assertEquals(TypeDescriptor.forObject(new CustomMap()).getMapKeyTypeDescriptor(), TypeDescriptor.valueOf(String.class));
assertEquals(TypeDescriptor.forObject(new CustomMap()).getMapValueTypeDescriptor(), TypeDescriptor.valueOf(Integer.class));
assertThat(TypeDescriptor.valueOf(String.class)).isEqualTo(TypeDescriptor.valueOf(CustomMap.class).getMapKeyTypeDescriptor());
assertThat(TypeDescriptor.valueOf(Integer.class)).isEqualTo(TypeDescriptor.valueOf(CustomMap.class).getMapValueTypeDescriptor());
assertThat(TypeDescriptor.valueOf(String.class)).isEqualTo(TypeDescriptor.forObject(new CustomMap()).getMapKeyTypeDescriptor());
assertThat(TypeDescriptor.valueOf(Integer.class)).isEqualTo(TypeDescriptor.forObject(new CustomMap()).getMapValueTypeDescriptor());
}
@Test
@@ -716,19 +708,19 @@ public class TypeDescriptorTests {
TypeDescriptor mapType = TypeDescriptor.map(
LinkedHashMap.class, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class));
TypeDescriptor arrayType = TypeDescriptor.array(mapType);
assertEquals(arrayType.getType(), LinkedHashMap[].class);
assertEquals(arrayType.getElementTypeDescriptor(), mapType);
assertThat(LinkedHashMap[].class).isEqualTo(arrayType.getType());
assertThat(mapType).isEqualTo(arrayType.getElementTypeDescriptor());
}
@Test
public void createStringArray() throws Exception {
TypeDescriptor arrayType = TypeDescriptor.array(TypeDescriptor.valueOf(String.class));
assertEquals(arrayType, TypeDescriptor.valueOf(String[].class));
assertThat(TypeDescriptor.valueOf(String[].class)).isEqualTo(arrayType);
}
@Test
public void createNullArray() throws Exception {
assertNull(TypeDescriptor.array(null));
assertThat((Object) TypeDescriptor.array(null)).isNull();
}
@Test

View File

@@ -40,11 +40,8 @@ import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/**
* @author Keith Donald
@@ -69,20 +66,21 @@ public class CollectionToCollectionConverterTests {
list.add("37");
TypeDescriptor sourceType = TypeDescriptor.forObject(list);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarListTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
try {
conversionService.convert(list, sourceType, targetType);
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
boolean condition = ex.getCause() instanceof ConverterNotFoundException;
assertThat(condition).isTrue();
}
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
@SuppressWarnings("unchecked")
List<Integer> result = (List<Integer>) conversionService.convert(list, sourceType, targetType);
assertFalse(list.equals(result));
assertEquals(9, result.get(0).intValue());
assertEquals(37, result.get(1).intValue());
assertThat(list.equals(result)).isFalse();
assertThat(result.get(0).intValue()).isEqualTo(9);
assertThat(result.get(1).intValue()).isEqualTo(37);
}
@Test
@@ -92,8 +90,8 @@ public class CollectionToCollectionConverterTests {
List<String> list = new ArrayList<>();
TypeDescriptor sourceType = TypeDescriptor.forObject(list);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("emptyListTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
assertEquals(list, conversionService.convert(list, sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
assertThat(conversionService.convert(list, sourceType, targetType)).isEqualTo(list);
}
@Test
@@ -103,11 +101,11 @@ public class CollectionToCollectionConverterTests {
List<String> list = new ArrayList<>();
TypeDescriptor sourceType = TypeDescriptor.forObject(list);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("emptyListDifferentTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
@SuppressWarnings("unchecked")
LinkedList<Integer> result = (LinkedList<Integer>) conversionService.convert(list, sourceType, targetType);
assertEquals(LinkedList.class, result.getClass());
assertTrue(result.isEmpty());
assertThat(result.getClass()).isEqualTo(LinkedList.class);
assertThat(result.isEmpty()).isTrue();
}
@Test
@@ -116,8 +114,8 @@ public class CollectionToCollectionConverterTests {
list.add(Arrays.asList("9", "12"));
list.add(Arrays.asList("37", "23"));
conversionService.addConverter(new CollectionToObjectConverter(conversionService));
assertTrue(conversionService.canConvert(List.class, List.class));
assertSame(list, conversionService.convert(list, List.class));
assertThat(conversionService.canConvert(List.class, List.class)).isTrue();
assertThat((Object) conversionService.convert(list, List.class)).isSameAs(list);
}
@Test
@@ -128,8 +126,8 @@ public class CollectionToCollectionConverterTests {
array[1] = Arrays.asList("37", "23");
conversionService.addConverter(new ArrayToCollectionConverter(conversionService));
conversionService.addConverter(new CollectionToObjectConverter(conversionService));
assertTrue(conversionService.canConvert(String[].class, List.class));
assertEquals(Arrays.asList(array), conversionService.convert(array, List.class));
assertThat(conversionService.canConvert(String[].class, List.class)).isTrue();
assertThat(conversionService.convert(array, List.class)).isEqualTo(Arrays.asList(array));
}
@Test
@@ -143,12 +141,12 @@ public class CollectionToCollectionConverterTests {
conversionService.addConverter(new CollectionToObjectConverter(conversionService));
TypeDescriptor sourceType = TypeDescriptor.forObject(list);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("objectToCollection"));
assertTrue(conversionService.canConvert(sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
List<List<List<Integer>>> result = (List<List<List<Integer>>>) conversionService.convert(list, sourceType, targetType);
assertEquals((Integer) 9, result.get(0).get(0).get(0));
assertEquals((Integer) 12, result.get(0).get(1).get(0));
assertEquals((Integer) 37, result.get(1).get(0).get(0));
assertEquals((Integer) 23, result.get(1).get(1).get(0));
assertThat(result.get(0).get(0).get(0)).isEqualTo((Integer) 9);
assertThat(result.get(0).get(1).get(0)).isEqualTo((Integer) 12);
assertThat(result.get(1).get(0).get(0)).isEqualTo((Integer) 37);
assertThat(result.get(1).get(1).get(0)).isEqualTo((Integer) 23);
}
@Test
@@ -163,12 +161,12 @@ public class CollectionToCollectionConverterTests {
conversionService.addConverter(new CollectionToObjectConverter(conversionService));
TypeDescriptor sourceType = TypeDescriptor.forObject(list);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("objectToCollection"));
assertTrue(conversionService.canConvert(sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
List<List<List<Integer>>> result = (List<List<List<Integer>>>) conversionService.convert(list, sourceType, targetType);
assertEquals((Integer) 9, result.get(0).get(0).get(0));
assertEquals((Integer) 12, result.get(0).get(0).get(1));
assertEquals((Integer) 37, result.get(1).get(0).get(0));
assertEquals((Integer) 23, result.get(1).get(0).get(1));
assertThat(result.get(0).get(0).get(0)).isEqualTo((Integer) 9);
assertThat(result.get(0).get(0).get(1)).isEqualTo((Integer) 12);
assertThat(result.get(1).get(0).get(0)).isEqualTo((Integer) 37);
assertThat(result.get(1).get(0).get(1)).isEqualTo((Integer) 23);
}
@Test
@@ -196,15 +194,16 @@ public class CollectionToCollectionConverterTests {
private void testCollectionConversionToArrayList(Collection<String> aSource) {
Object myConverted = (new CollectionToCollectionConverter(new GenericConversionService())).convert(
aSource, TypeDescriptor.forObject(aSource), TypeDescriptor.forObject(new ArrayList()));
assertTrue(myConverted instanceof ArrayList<?>);
assertEquals(aSource.size(), ((ArrayList<?>) myConverted).size());
boolean condition = myConverted instanceof ArrayList<?>;
assertThat(condition).isTrue();
assertThat(((ArrayList<?>) myConverted).size()).isEqualTo(aSource.size());
}
@Test
public void listToCollectionNoCopyRequired() throws NoSuchFieldException {
List<?> input = new ArrayList<>(Arrays.asList("foo", "bar"));
assertSame(input, conversionService.convert(input, TypeDescriptor.forObject(input),
new TypeDescriptor(getClass().getField("wildcardCollection"))));
assertThat(conversionService.convert(input, TypeDescriptor.forObject(input),
new TypeDescriptor(getClass().getField("wildcardCollection")))).isSameAs(input);
}
@Test
@@ -214,7 +213,7 @@ public class CollectionToCollectionConverterTests {
resources.add(new FileSystemResource("test"));
resources.add(new TestResource());
TypeDescriptor sourceType = TypeDescriptor.forObject(resources);
assertSame(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources"))));
assertThat(conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))).isSameAs(resources);
}
@Test
@@ -225,7 +224,7 @@ public class CollectionToCollectionConverterTests {
resources.add(new FileSystemResource("test"));
resources.add(new TestResource());
TypeDescriptor sourceType = TypeDescriptor.forObject(resources);
assertSame(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources"))));
assertThat(conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))).isSameAs(resources);
}
@Test
@@ -234,7 +233,7 @@ public class CollectionToCollectionConverterTests {
resources.add(null);
resources.add(null);
TypeDescriptor sourceType = TypeDescriptor.forObject(resources);
assertSame(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources"))));
assertThat(conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))).isSameAs(resources);
}
@Test
@@ -263,8 +262,7 @@ public class CollectionToCollectionConverterTests {
List<String> list = new ArrayList<>();
list.add("A");
list.add("C");
assertEquals(EnumSet.of(MyEnum.A, MyEnum.C),
conversionService.convert(list, TypeDescriptor.forObject(list), new TypeDescriptor(getClass().getField("enumSet"))));
assertThat(conversionService.convert(list, TypeDescriptor.forObject(list), new TypeDescriptor(getClass().getField("enumSet")))).isEqualTo(EnumSet.of(MyEnum.A, MyEnum.C));
}

View File

@@ -55,12 +55,6 @@ 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.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for {@link GenericConversionService}.
@@ -80,17 +74,17 @@ public class GenericConversionServiceTests {
@Test
public void canConvert() {
assertFalse(conversionService.canConvert(String.class, Integer.class));
assertThat(conversionService.canConvert(String.class, Integer.class)).isFalse();
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(String.class, Integer.class));
assertThat(conversionService.canConvert(String.class, Integer.class)).isTrue();
}
@Test
public void canConvertAssignable() {
assertTrue(conversionService.canConvert(String.class, String.class));
assertTrue(conversionService.canConvert(Integer.class, Number.class));
assertTrue(conversionService.canConvert(boolean.class, boolean.class));
assertTrue(conversionService.canConvert(boolean.class, Boolean.class));
assertThat(conversionService.canConvert(String.class, String.class)).isTrue();
assertThat(conversionService.canConvert(Integer.class, Number.class)).isTrue();
assertThat(conversionService.canConvert(boolean.class, boolean.class)).isTrue();
assertThat(conversionService.canConvert(boolean.class, Boolean.class)).isTrue();
}
@Test
@@ -107,19 +101,19 @@ public class GenericConversionServiceTests {
@Test
public void canConvertNullSourceType() {
assertTrue(conversionService.canConvert(null, Integer.class));
assertTrue(conversionService.canConvert(null, TypeDescriptor.valueOf(Integer.class)));
assertThat(conversionService.canConvert(null, Integer.class)).isTrue();
assertThat(conversionService.canConvert(null, TypeDescriptor.valueOf(Integer.class))).isTrue();
}
@Test
public void convert() {
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertEquals(Integer.valueOf(3), conversionService.convert("3", Integer.class));
assertThat(conversionService.convert("3", Integer.class)).isEqualTo((int) Integer.valueOf(3));
}
@Test
public void convertNullSource() {
assertEquals(null, conversionService.convert(null, Integer.class));
assertThat(conversionService.convert(null, Integer.class)).isEqualTo(null);
}
@Test
@@ -142,8 +136,8 @@ public class GenericConversionServiceTests {
@Test
public void convertAssignableSource() {
assertEquals(Boolean.FALSE, conversionService.convert(false, boolean.class));
assertEquals(Boolean.FALSE, conversionService.convert(false, Boolean.class));
assertThat(conversionService.convert(false, boolean.class)).isEqualTo(Boolean.FALSE);
assertThat(conversionService.convert(false, Boolean.class)).isEqualTo(Boolean.FALSE);
}
@Test
@@ -160,17 +154,17 @@ public class GenericConversionServiceTests {
@Test
public void sourceTypeIsVoid() {
assertFalse(conversionService.canConvert(void.class, String.class));
assertThat(conversionService.canConvert(void.class, String.class)).isFalse();
}
@Test
public void targetTypeIsVoid() {
assertFalse(conversionService.canConvert(String.class, void.class));
assertThat(conversionService.canConvert(String.class, void.class)).isFalse();
}
@Test
public void convertNull() {
assertNull(conversionService.convert(null, Integer.class));
assertThat(conversionService.convert(null, Integer.class)).isNull();
}
@Test
@@ -207,7 +201,7 @@ public class GenericConversionServiceTests {
}
});
Integer result = conversionService.convert("3", Integer.class);
assertEquals(Integer.valueOf(3), result);
assertThat((int) result).isEqualTo((int) Integer.valueOf(3));
}
// SPR-8718
@@ -220,29 +214,29 @@ public class GenericConversionServiceTests {
@Test
public void convertObjectToPrimitive() {
assertFalse(conversionService.canConvert(String.class, boolean.class));
assertThat(conversionService.canConvert(String.class, boolean.class)).isFalse();
conversionService.addConverter(new StringToBooleanConverter());
assertTrue(conversionService.canConvert(String.class, boolean.class));
assertThat(conversionService.canConvert(String.class, boolean.class)).isTrue();
Boolean b = conversionService.convert("true", boolean.class);
assertTrue(b);
assertTrue(conversionService.canConvert(TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(boolean.class)));
assertThat(b).isTrue();
assertThat(conversionService.canConvert(TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(boolean.class))).isTrue();
b = (Boolean) conversionService.convert("true", TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(boolean.class));
assertTrue(b);
assertThat(b).isTrue();
}
@Test
public void convertObjectToPrimitiveViaConverterFactory() {
assertFalse(conversionService.canConvert(String.class, int.class));
assertThat(conversionService.canConvert(String.class, int.class)).isFalse();
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(String.class, int.class));
assertThat(conversionService.canConvert(String.class, int.class)).isTrue();
Integer three = conversionService.convert("3", int.class);
assertEquals(3, three.intValue());
assertThat(three.intValue()).isEqualTo(3);
}
@Test
public void genericConverterDelegatingBackToConversionServiceConverterNotFound() {
conversionService.addConverter(new ObjectToArrayConverter(conversionService));
assertFalse(conversionService.canConvert(String.class, Integer[].class));
assertThat(conversionService.canConvert(String.class, Integer[].class)).isFalse();
assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() ->
conversionService.convert("3,4,5", Integer[].class));
}
@@ -253,7 +247,7 @@ public class GenericConversionServiceTests {
raw.add("one");
raw.add("two");
Object converted = conversionService.convert(raw, Iterable.class);
assertSame(raw, converted);
assertThat(converted).isSameAs(raw);
}
@Test
@@ -262,7 +256,7 @@ public class GenericConversionServiceTests {
raw.add("one");
raw.add("two");
Object converted = conversionService.convert(raw, Object.class);
assertSame(raw, converted);
assertThat(converted).isSameAs(raw);
}
@Test
@@ -270,7 +264,7 @@ public class GenericConversionServiceTests {
Map<Object, Object> raw = new HashMap<>();
raw.put("key", "value");
Object converted = conversionService.convert(raw, Object.class);
assertSame(raw, converted);
assertThat(converted).isSameAs(raw);
}
@Test
@@ -278,7 +272,7 @@ public class GenericConversionServiceTests {
conversionService.addConverter(new MyBaseInterfaceToStringConverter());
conversionService.addConverter(new ObjectToStringConverter());
Object converted = conversionService.convert(new MyInterfaceImplementer(), String.class);
assertEquals("RESULT", converted);
assertThat(converted).isEqualTo("RESULT");
}
@Test
@@ -286,7 +280,7 @@ public class GenericConversionServiceTests {
conversionService.addConverter(new MyBaseInterfaceToStringConverter());
conversionService.addConverter(new ArrayToArrayConverter(conversionService));
String[] converted = conversionService.convert(new MyInterface[] {new MyInterfaceImplementer()}, String[].class);
assertEquals("RESULT", converted[0]);
assertThat(converted[0]).isEqualTo("RESULT");
}
@Test
@@ -294,7 +288,7 @@ public class GenericConversionServiceTests {
conversionService.addConverter(new MyBaseInterfaceToStringConverter());
conversionService.addConverter(new ArrayToArrayConverter(conversionService));
String[] converted = conversionService.convert(new MyInterfaceImplementer[] {new MyInterfaceImplementer()}, String[].class);
assertEquals("RESULT", converted[0]);
assertThat(converted[0]).isEqualTo("RESULT");
}
@Test
@@ -302,21 +296,21 @@ public class GenericConversionServiceTests {
conversionService.addConverter(new MyStringArrayToResourceArrayConverter());
Resource[] converted = conversionService.convert(new String[] { "x1", "z3" }, Resource[].class);
List<String> descriptions = Arrays.stream(converted).map(Resource::getDescription).sorted(naturalOrder()).collect(toList());
assertEquals(Arrays.asList("1", "3"), descriptions);
assertThat(descriptions).isEqualTo(Arrays.asList("1", "3"));
}
@Test
public void testStringArrayToIntegerArray() {
conversionService.addConverter(new MyStringArrayToIntegerArrayConverter());
Integer[] converted = conversionService.convert(new String[] {"x1", "z3"}, Integer[].class);
assertArrayEquals(new Integer[] { 1, 3 }, converted);
assertThat(converted).isEqualTo(new Integer[] { 1, 3 });
}
@Test
public void testStringToIntegerArray() {
conversionService.addConverter(new MyStringToIntegerArrayConverter());
Integer[] converted = conversionService.convert("x1,z3", Integer[].class);
assertArrayEquals(new Integer[] { 1, 3 }, converted);
assertThat(converted).isEqualTo(new Integer[] { 1, 3 });
}
@Test
@@ -324,28 +318,28 @@ public class GenericConversionServiceTests {
Map<String, String> input = new LinkedHashMap<>();
input.put("key", "value");
Object converted = conversionService.convert(input, TypeDescriptor.forObject(input), new TypeDescriptor(getClass().getField("wildcardMap")));
assertEquals(input, converted);
assertThat(converted).isEqualTo(input);
}
@Test
public void testStringToString() {
String value = "myValue";
String result = conversionService.convert(value, String.class);
assertSame(value, result);
assertThat(result).isSameAs(value);
}
@Test
public void testStringToObject() {
String value = "myValue";
Object result = conversionService.convert(value, Object.class);
assertSame(value, result);
assertThat(result).isSameAs(value);
}
@Test
public void testIgnoreCopyConstructor() {
WithCopyConstructor value = new WithCopyConstructor();
Object result = conversionService.convert(value, WithCopyConstructor.class);
assertSame(value, result);
assertThat(result).isSameAs(value);
}
@Test
@@ -403,8 +397,8 @@ public class GenericConversionServiceTests {
List<String> list = new ArrayList<>();
TypeDescriptor sourceType = TypeDescriptor.forObject(list);
TypeDescriptor targetType = TypeDescriptor.valueOf(String[].class);
assertTrue(conversionService.canConvert(sourceType, targetType));
assertEquals(0, ((String[]) conversionService.convert(list, sourceType, targetType)).length);
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
assertThat(((String[]) conversionService.convert(list, sourceType, targetType)).length).isEqualTo(0);
}
@Test
@@ -414,26 +408,26 @@ public class GenericConversionServiceTests {
List<String> list = new ArrayList<>();
TypeDescriptor sourceType = TypeDescriptor.forObject(list);
TypeDescriptor targetType = TypeDescriptor.valueOf(Integer.class);
assertTrue(conversionService.canConvert(sourceType, targetType));
assertNull(conversionService.convert(list, sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
assertThat(conversionService.convert(list, sourceType, targetType)).isNull();
}
@Test
public void stringToArrayCanConvert() {
conversionService.addConverter(new StringToArrayConverter(conversionService));
assertFalse(conversionService.canConvert(String.class, Integer[].class));
assertThat(conversionService.canConvert(String.class, Integer[].class)).isFalse();
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(String.class, Integer[].class));
assertThat(conversionService.canConvert(String.class, Integer[].class)).isTrue();
}
@Test
public void stringToCollectionCanConvert() throws Exception {
conversionService.addConverter(new StringToCollectionConverter(conversionService));
assertTrue(conversionService.canConvert(String.class, Collection.class));
assertThat(conversionService.canConvert(String.class, Collection.class)).isTrue();
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("integerCollection"));
assertFalse(conversionService.canConvert(TypeDescriptor.valueOf(String.class), targetType));
assertThat(conversionService.canConvert(TypeDescriptor.valueOf(String.class), targetType)).isFalse();
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(TypeDescriptor.valueOf(String.class), targetType));
assertThat(conversionService.canConvert(TypeDescriptor.valueOf(String.class), targetType)).isTrue();
}
@Test
@@ -447,16 +441,16 @@ public class GenericConversionServiceTests {
public void testConvertiblePairEqualsAndHash() {
GenericConverter.ConvertiblePair pair = new GenericConverter.ConvertiblePair(Number.class, String.class);
GenericConverter.ConvertiblePair pairEqual = new GenericConverter.ConvertiblePair(Number.class, String.class);
assertEquals(pair, pairEqual);
assertEquals(pair.hashCode(), pairEqual.hashCode());
assertThat(pairEqual).isEqualTo(pair);
assertThat(pairEqual.hashCode()).isEqualTo(pair.hashCode());
}
@Test
public void testConvertiblePairDifferentEqualsAndHash() {
GenericConverter.ConvertiblePair pair = new GenericConverter.ConvertiblePair(Number.class, String.class);
GenericConverter.ConvertiblePair pairOpposite = new GenericConverter.ConvertiblePair(String.class, Number.class);
assertFalse(pair.equals(pairOpposite));
assertFalse(pair.hashCode() == pairOpposite.hashCode());
assertThat(pair.equals(pairOpposite)).isFalse();
assertThat(pair.hashCode() == pairOpposite.hashCode()).isFalse();
}
@Test
@@ -474,9 +468,9 @@ public class GenericConversionServiceTests {
@Test
public void removeConvertible() {
conversionService.addConverter(new ColorConverter());
assertTrue(conversionService.canConvert(String.class, Color.class));
assertThat(conversionService.canConvert(String.class, Color.class)).isTrue();
conversionService.removeConvertible(String.class, Color.class);
assertFalse(conversionService.canConvert(String.class, Color.class));
assertThat(conversionService.canConvert(String.class, Color.class)).isFalse();
}
@Test
@@ -484,8 +478,8 @@ public class GenericConversionServiceTests {
MyConditionalConverter converter = new MyConditionalConverter();
conversionService.addConverter(new ColorConverter());
conversionService.addConverter(converter);
assertEquals(Color.BLACK, conversionService.convert("#000000", Color.class));
assertTrue(converter.getMatchAttempts() > 0);
assertThat(conversionService.convert("#000000", Color.class)).isEqualTo(Color.BLACK);
assertThat(converter.getMatchAttempts() > 0).isTrue();
}
@Test
@@ -493,9 +487,9 @@ public class GenericConversionServiceTests {
MyConditionalConverterFactory converter = new MyConditionalConverterFactory();
conversionService.addConverter(new ColorConverter());
conversionService.addConverterFactory(converter);
assertEquals(Color.BLACK, conversionService.convert("#000000", Color.class));
assertTrue(converter.getMatchAttempts() > 0);
assertTrue(converter.getNestedMatchAttempts() > 0);
assertThat(conversionService.convert("#000000", Color.class)).isEqualTo(Color.BLACK);
assertThat(converter.getMatchAttempts() > 0).isTrue();
assertThat(converter.getNestedMatchAttempts() > 0).isTrue();
}
@Test
@@ -503,14 +497,14 @@ public class GenericConversionServiceTests {
conversionService.addConverter(new ColorConverter());
conversionService.addConverter(new MyConditionalColorConverter());
assertEquals(Color.BLACK, conversionService.convert("000000xxxx",
new TypeDescriptor(getClass().getField("activeColor"))));
assertEquals(Color.BLACK, conversionService.convert(" #000000 ",
new TypeDescriptor(getClass().getField("inactiveColor"))));
assertEquals(Color.BLACK, conversionService.convert("000000yyyy",
new TypeDescriptor(getClass().getField("activeColor"))));
assertEquals(Color.BLACK, conversionService.convert(" #000000 ",
new TypeDescriptor(getClass().getField("inactiveColor"))));
assertThat(conversionService.convert("000000xxxx",
new TypeDescriptor(getClass().getField("activeColor")))).isEqualTo(Color.BLACK);
assertThat(conversionService.convert(" #000000 ",
new TypeDescriptor(getClass().getField("inactiveColor")))).isEqualTo(Color.BLACK);
assertThat(conversionService.convert("000000yyyy",
new TypeDescriptor(getClass().getField("activeColor")))).isEqualTo(Color.BLACK);
assertThat(conversionService.convert(" #000000 ",
new TypeDescriptor(getClass().getField("inactiveColor")))).isEqualTo(Color.BLACK);
}
@Test
@@ -525,9 +519,9 @@ public class GenericConversionServiceTests {
public void conditionalConversionForAllTypes() {
MyConditionalGenericConverter converter = new MyConditionalGenericConverter();
conversionService.addConverter(converter);
assertEquals((Integer) 3, conversionService.convert(3, Integer.class));
assertThat(conversionService.convert(3, Integer.class)).isEqualTo(3);
assertThat(converter.getSourceTypes().size()).isGreaterThan(2);
assertTrue(converter.getSourceTypes().stream().allMatch(td -> Integer.class.equals(td.getType())));
assertThat(converter.getSourceTypes().stream().allMatch(td -> Integer.class.equals(td.getType()))).isTrue();
}
@Test
@@ -535,19 +529,19 @@ public class GenericConversionServiceTests {
// SPR-9566
byte[] byteArray = new byte[] { 1, 2, 3 };
byte[] converted = conversionService.convert(byteArray, byte[].class);
assertSame(byteArray, converted);
assertThat(converted).isSameAs(byteArray);
}
@Test
public void testEnumToStringConversion() {
conversionService.addConverter(new EnumToStringConverter(conversionService));
assertEquals("A", conversionService.convert(MyEnum.A, String.class));
assertThat(conversionService.convert(MyEnum.A, String.class)).isEqualTo("A");
}
@Test
public void testSubclassOfEnumToString() throws Exception {
conversionService.addConverter(new EnumToStringConverter(conversionService));
assertEquals("FIRST", conversionService.convert(EnumWithSubclass.FIRST, String.class));
assertThat(conversionService.convert(EnumWithSubclass.FIRST, String.class)).isEqualTo("FIRST");
}
@Test
@@ -555,21 +549,21 @@ public class GenericConversionServiceTests {
// SPR-9692
conversionService.addConverter(new EnumToStringConverter(conversionService));
conversionService.addConverter(new MyEnumInterfaceToStringConverter<MyEnum>());
assertEquals("1", conversionService.convert(MyEnum.A, String.class));
assertThat(conversionService.convert(MyEnum.A, String.class)).isEqualTo("1");
}
@Test
public void testStringToEnumWithInterfaceConversion() {
conversionService.addConverterFactory(new StringToEnumConverterFactory());
conversionService.addConverterFactory(new StringToMyEnumInterfaceConverterFactory());
assertEquals(MyEnum.A, conversionService.convert("1", MyEnum.class));
assertThat(conversionService.convert("1", MyEnum.class)).isEqualTo(MyEnum.A);
}
@Test
public void testStringToEnumWithBaseInterfaceConversion() {
conversionService.addConverterFactory(new StringToEnumConverterFactory());
conversionService.addConverterFactory(new StringToMyEnumBaseInterfaceConverterFactory());
assertEquals(MyEnum.A, conversionService.convert("base1", MyEnum.class));
assertThat(conversionService.convert("base1", MyEnum.class)).isEqualTo(MyEnum.A);
}
@Test
@@ -587,36 +581,24 @@ public class GenericConversionServiceTests {
conversionService.addConverter(new MyStringToStringCollectionConverter());
conversionService.addConverter(new MyStringToIntegerCollectionConverter());
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection"))));
assertEquals(Collections.singleton(4),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection"))));
assertEquals(Collections.singleton(4),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection"))));
assertEquals(Collections.singleton(4),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection"))));
assertEquals(Collections.singleton(4),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection"))));
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection"))));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))).isEqualTo(Collections.singleton("testX"));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection")))).isEqualTo(Collections.singleton(4));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))).isEqualTo(Collections.singleton(4));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection")))).isEqualTo(Collections.singleton(4));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))).isEqualTo(Collections.singleton(4));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))).isEqualTo(Collections.singleton("testX"));
}
@Test
public void adaptedCollectionTypesFromSameSourceType() throws Exception {
conversionService.addConverter(new MyStringToStringCollectionConverter());
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection"))));
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection"))));
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection"))));
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection"))));
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection"))));
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection"))));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))).isEqualTo(Collections.singleton("testX"));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection")))).isEqualTo(Collections.singleton("testX"));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))).isEqualTo(Collections.singleton("testX"));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection")))).isEqualTo(Collections.singleton("testX"));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))).isEqualTo(Collections.singleton("testX"));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))).isEqualTo(Collections.singleton("testX"));
assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() ->
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection"))));
@@ -626,32 +608,24 @@ public class GenericConversionServiceTests {
public void genericCollectionAsSource() throws Exception {
conversionService.addConverter(new MyStringToGenericCollectionConverter());
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection"))));
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection"))));
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection"))));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))).isEqualTo(Collections.singleton("testX"));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection")))).isEqualTo(Collections.singleton("testX"));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))).isEqualTo(Collections.singleton("testX"));
// The following is unpleasant but a consequence of the generic collection converter above...
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection"))));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection")))).isEqualTo(Collections.singleton("testX"));
}
@Test
public void rawCollectionAsSource() throws Exception {
conversionService.addConverter(new MyStringToRawCollectionConverter());
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection"))));
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection"))));
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection"))));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))).isEqualTo(Collections.singleton("testX"));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection")))).isEqualTo(Collections.singleton("testX"));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))).isEqualTo(Collections.singleton("testX"));
// The following is unpleasant but a consequence of the raw collection converter above...
assertEquals(Collections.singleton("testX"),
conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection"))));
assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection")))).isEqualTo(Collections.singleton("testX"));
}

View File

@@ -35,10 +35,6 @@ import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/**
* @author Keith Donald
@@ -64,21 +60,21 @@ public class MapToMapConverterTests {
TypeDescriptor sourceType = TypeDescriptor.forObject(map);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarMapTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
try {
conversionService.convert(map, sourceType, targetType);
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
assertThat(ex.getCause() instanceof ConverterNotFoundException).isTrue();
}
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
@SuppressWarnings("unchecked")
Map<Integer, Integer> result = (Map<Integer, Integer>) conversionService.convert(map, sourceType, targetType);
assertFalse(map.equals(result));
assertEquals((Integer) 9, result.get(1));
assertEquals((Integer) 37, result.get(2));
assertThat(map.equals(result)).isFalse();
assertThat((int) result.get(1)).isEqualTo(9);
assertThat((int) result.get(2)).isEqualTo(37);
}
@Test
@@ -87,8 +83,8 @@ public class MapToMapConverterTests {
map.put("1", "9");
map.put("2", "37");
assertTrue(conversionService.canConvert(Map.class, Map.class));
assertSame(map, conversionService.convert(map, Map.class));
assertThat(conversionService.canConvert(Map.class, Map.class)).isTrue();
assertThat((Map<?, ?>) conversionService.convert(map, Map.class)).isSameAs(map);
}
@Test
@@ -99,21 +95,21 @@ public class MapToMapConverterTests {
TypeDescriptor sourceType = new TypeDescriptor(getClass().getField("notGenericMapSource"));
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarMapTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
try {
conversionService.convert(map, sourceType, targetType);
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
assertThat(ex.getCause() instanceof ConverterNotFoundException).isTrue();
}
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
@SuppressWarnings("unchecked")
Map<Integer, Integer> result = (Map<Integer, Integer>) conversionService.convert(map, sourceType, targetType);
assertFalse(map.equals(result));
assertEquals((Integer) 9, result.get(1));
assertEquals((Integer) 37, result.get(2));
assertThat(map.equals(result)).isFalse();
assertThat((int) result.get(1)).isEqualTo(9);
assertThat((int) result.get(2)).isEqualTo(37);
}
@Test
@@ -124,22 +120,22 @@ public class MapToMapConverterTests {
TypeDescriptor sourceType = TypeDescriptor.forObject(map);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("collectionMapTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
try {
conversionService.convert(map, sourceType, targetType);
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
assertThat(ex.getCause() instanceof ConverterNotFoundException).isTrue();
}
conversionService.addConverter(new CollectionToCollectionConverter(conversionService));
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
@SuppressWarnings("unchecked")
Map<Integer, List<Integer>> result = (Map<Integer, List<Integer>>) conversionService.convert(map, sourceType, targetType);
assertFalse(map.equals(result));
assertEquals(Arrays.asList(9, 12), result.get(1));
assertEquals(Arrays.asList(37, 23), result.get(2));
assertThat(map.equals(result)).isFalse();
assertThat(result.get(1)).isEqualTo(Arrays.asList(9, 12));
assertThat(result.get(2)).isEqualTo(Arrays.asList(37, 23));
}
@Test
@@ -150,18 +146,18 @@ public class MapToMapConverterTests {
TypeDescriptor sourceType = new TypeDescriptor(getClass().getField("sourceCollectionMapTarget"));
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("collectionMapTarget"));
assertFalse(conversionService.canConvert(sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isFalse();
assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() ->
conversionService.convert(map, sourceType, targetType));
conversionService.addConverter(new CollectionToCollectionConverter(conversionService));
conversionService.addConverterFactory(new StringToNumberConverterFactory());
assertTrue(conversionService.canConvert(sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
@SuppressWarnings("unchecked")
Map<Integer, List<Integer>> result = (Map<Integer, List<Integer>>) conversionService.convert(map, sourceType, targetType);
assertFalse(map.equals(result));
assertEquals(Arrays.asList(9, 12), result.get(1));
assertEquals(Arrays.asList(37, 23), result.get(2));
assertThat(map.equals(result)).isFalse();
assertThat(result.get(1)).isEqualTo(Arrays.asList(9, 12));
assertThat(result.get(2)).isEqualTo(Arrays.asList(37, 23));
}
@Test
@@ -170,8 +166,8 @@ public class MapToMapConverterTests {
map.put("1", Arrays.asList("9", "12"));
map.put("2", Arrays.asList("37", "23"));
assertTrue(conversionService.canConvert(Map.class, Map.class));
assertSame(map, conversionService.convert(map, Map.class));
assertThat(conversionService.canConvert(Map.class, Map.class)).isTrue();
assertThat((Map<?, ?>) conversionService.convert(map, Map.class)).isSameAs(map);
}
@Test
@@ -182,8 +178,8 @@ public class MapToMapConverterTests {
conversionService.addConverter(new CollectionToCollectionConverter(conversionService));
conversionService.addConverter(new CollectionToObjectConverter(conversionService));
assertTrue(conversionService.canConvert(Map.class, Map.class));
assertSame(map, conversionService.convert(map, Map.class));
assertThat(conversionService.canConvert(Map.class, Map.class)).isTrue();
assertThat((Map<?, ?>) conversionService.convert(map, Map.class)).isSameAs(map);
}
@Test
@@ -192,16 +188,16 @@ public class MapToMapConverterTests {
TypeDescriptor sourceType = TypeDescriptor.forObject(map);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("emptyMapTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
assertSame(map, conversionService.convert(map, sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
assertThat(conversionService.convert(map, sourceType, targetType)).isSameAs(map);
}
@Test
public void emptyMapNoTargetGenericInfo() throws Exception {
Map<String, String> map = new HashMap<>();
assertTrue(conversionService.canConvert(Map.class, Map.class));
assertSame(map, conversionService.convert(map, Map.class));
assertThat(conversionService.canConvert(Map.class, Map.class)).isTrue();
assertThat((Map<?, ?>) conversionService.convert(map, Map.class)).isSameAs(map);
}
@Test
@@ -210,11 +206,11 @@ public class MapToMapConverterTests {
TypeDescriptor sourceType = TypeDescriptor.forObject(map);
TypeDescriptor targetType = new TypeDescriptor(getClass().getField("emptyMapDifferentTarget"));
assertTrue(conversionService.canConvert(sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
@SuppressWarnings("unchecked")
LinkedHashMap<String, String> result = (LinkedHashMap<String, String>) conversionService.convert(map, sourceType, targetType);
assertEquals(map, result);
assertEquals(LinkedHashMap.class, result.getClass());
assertThat(result).isEqualTo(map);
assertThat(result.getClass()).isEqualTo(LinkedHashMap.class);
}
@Test
@@ -227,11 +223,11 @@ public class MapToMapConverterTests {
TypeDescriptor targetType = TypeDescriptor.map(NoDefaultConstructorMap.class,
TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class));
assertTrue(conversionService.canConvert(sourceType, targetType));
assertThat(conversionService.canConvert(sourceType, targetType)).isTrue();
@SuppressWarnings("unchecked")
Map<String, Integer> result = (Map<String, Integer>) conversionService.convert(map, sourceType, targetType);
assertEquals(map, result);
assertEquals(NoDefaultConstructorMap.class, result.getClass());
assertThat(result).isEqualTo(map);
assertThat(result.getClass()).isEqualTo(NoDefaultConstructorMap.class);
}
@Test
@@ -274,8 +270,8 @@ public class MapToMapConverterTests {
result.put(MyEnum.A, 1);
result.put(MyEnum.C, 2);
assertEquals(result, conversionService.convert(source,
TypeDescriptor.forObject(source), new TypeDescriptor(getClass().getField("enumMap"))));
assertThat(conversionService.convert(source,
TypeDescriptor.forObject(source), new TypeDescriptor(getClass().getField("enumMap")))).isEqualTo(result);
}

View File

@@ -28,12 +28,9 @@ import org.springframework.core.convert.ConverterNotFoundException;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.Converter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Tests for {@link StreamConverter}.
@@ -64,14 +61,15 @@ public class StreamConverterTests {
TypeDescriptor listOfStrings = new TypeDescriptor(Types.class.getField("listOfStrings"));
Object result = this.conversionService.convert(stream, listOfStrings);
assertNotNull("Converted object must not be null", result);
assertTrue("Converted object must be a list", result instanceof List);
assertThat(result).as("Converted object must not be null").isNotNull();
boolean condition = result instanceof List;
assertThat(condition).as("Converted object must be a list").isTrue();
@SuppressWarnings("unchecked")
List<String> content = (List<String>) result;
assertEquals("1", content.get(0));
assertEquals("2", content.get(1));
assertEquals("3", content.get(2));
assertEquals("Wrong number of elements", 3, content.size());
assertThat(content.get(0)).isEqualTo("1");
assertThat(content.get(1)).isEqualTo("2");
assertThat(content.get(2)).isEqualTo("3");
assertThat(content.size()).as("Wrong number of elements").isEqualTo(3);
}
@Test
@@ -81,13 +79,13 @@ public class StreamConverterTests {
TypeDescriptor arrayOfLongs = new TypeDescriptor(Types.class.getField("arrayOfLongs"));
Object result = this.conversionService.convert(stream, arrayOfLongs);
assertNotNull("Converted object must not be null", result);
assertTrue("Converted object must be an array", result.getClass().isArray());
assertThat(result).as("Converted object must not be null").isNotNull();
assertThat(result.getClass().isArray()).as("Converted object must be an array").isTrue();
Long[] content = (Long[]) result;
assertEquals(Long.valueOf(1L), content[0]);
assertEquals(Long.valueOf(2L), content[1]);
assertEquals(Long.valueOf(3L), content[2]);
assertEquals("Wrong number of elements", 3, content.length);
assertThat(content[0]).isEqualTo(Long.valueOf(1L));
assertThat(content[1]).isEqualTo(Long.valueOf(2L));
assertThat(content[2]).isEqualTo(Long.valueOf(3L));
assertThat(content.length).as("Wrong number of elements").isEqualTo(3);
}
@Test
@@ -96,14 +94,15 @@ public class StreamConverterTests {
TypeDescriptor listOfStrings = new TypeDescriptor(Types.class.getField("rawList"));
Object result = this.conversionService.convert(stream, listOfStrings);
assertNotNull("Converted object must not be null", result);
assertTrue("Converted object must be a list", result instanceof List);
assertThat(result).as("Converted object must not be null").isNotNull();
boolean condition = result instanceof List;
assertThat(condition).as("Converted object must be a list").isTrue();
@SuppressWarnings("unchecked")
List<Object> content = (List<Object>) result;
assertEquals(1, content.get(0));
assertEquals(2, content.get(1));
assertEquals(3, content.get(2));
assertEquals("Wrong number of elements", 3, content.size());
assertThat(content.get(0)).isEqualTo(1);
assertThat(content.get(1)).isEqualTo(2);
assertThat(content.get(2)).isEqualTo(3);
assertThat(content.size()).as("Wrong number of elements").isEqualTo(3);
}
@Test
@@ -123,11 +122,12 @@ public class StreamConverterTests {
TypeDescriptor streamOfInteger = new TypeDescriptor(Types.class.getField("streamOfIntegers"));
Object result = this.conversionService.convert(stream, streamOfInteger);
assertNotNull("Converted object must not be null", result);
assertTrue("Converted object must be a stream", result instanceof Stream);
assertThat(result).as("Converted object must not be null").isNotNull();
boolean condition = result instanceof Stream;
assertThat(condition).as("Converted object must be a stream").isTrue();
@SuppressWarnings("unchecked")
Stream<Integer> content = (Stream<Integer>) result;
assertEquals(6, content.mapToInt(x -> x).sum());
assertThat(content.mapToInt(x -> x).sum()).isEqualTo(6);
}
@Test
@@ -143,11 +143,12 @@ public class StreamConverterTests {
TypeDescriptor streamOfBoolean = new TypeDescriptor(Types.class.getField("streamOfBooleans"));
Object result = this.conversionService.convert(stream, streamOfBoolean);
assertNotNull("Converted object must not be null", result);
assertTrue("Converted object must be a stream", result instanceof Stream);
assertThat(result).as("Converted object must not be null").isNotNull();
boolean condition = result instanceof Stream;
assertThat(condition).as("Converted object must be a stream").isTrue();
@SuppressWarnings("unchecked")
Stream<Boolean> content = (Stream<Boolean>) result;
assertEquals(2, content.filter(x -> x).count());
assertThat(content.filter(x -> x).count()).isEqualTo(2);
}
@Test
@@ -157,20 +158,21 @@ public class StreamConverterTests {
TypeDescriptor streamOfInteger = new TypeDescriptor(Types.class.getField("rawStream"));
Object result = this.conversionService.convert(stream, streamOfInteger);
assertNotNull("Converted object must not be null", result);
assertTrue("Converted object must be a stream", result instanceof Stream);
assertThat(result).as("Converted object must not be null").isNotNull();
boolean condition = result instanceof Stream;
assertThat(condition).as("Converted object must be a stream").isTrue();
@SuppressWarnings("unchecked")
Stream<Object> content = (Stream<Object>) result;
StringBuilder sb = new StringBuilder();
content.forEach(sb::append);
assertEquals("123", sb.toString());
assertThat(sb.toString()).isEqualTo("123");
}
@Test
public void doesNotMatchIfNoStream() throws NoSuchFieldException {
assertFalse("Should not match non stream type", this.streamConverter.matches(
assertThat(this.streamConverter.matches(
new TypeDescriptor(Types.class.getField("listOfStrings")),
new TypeDescriptor(Types.class.getField("arrayOfLongs"))));
new TypeDescriptor(Types.class.getField("arrayOfLongs")))).as("Should not match non stream type").isFalse();
}
@Test

View File

@@ -20,7 +20,7 @@ import java.util.Collections;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link CompositePropertySource}.
@@ -43,7 +43,7 @@ public class CompositePropertySourceTests {
int i1 = s.indexOf("name='p1'");
int i2 = s.indexOf("name='p2'");
int i3 = s.indexOf("name='p3'");
assertTrue("Bad order: " + s, ((i1 < i2) && (i2 < i3)));
assertThat(((i1 < i2) && (i2 < i3))).as("Bad order: " + s).isTrue();
}
}

View File

@@ -23,7 +23,6 @@ import joptsimple.OptionSet;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
/**
* Unit tests for {@link JOptCommandLinePropertySource}.
@@ -75,7 +74,7 @@ public class JOptCommandLinePropertySourceTests {
OptionSet options = parser.parse("--foo=bar,baz,biz");
CommandLinePropertySource<?> ps = new JOptCommandLinePropertySource(options);
assertEquals(Arrays.asList("bar","baz","biz"), ps.getOptionValues("foo"));
assertThat(ps.getOptionValues("foo")).isEqualTo(Arrays.asList("bar","baz","biz"));
assertThat(ps.getProperty("foo")).isEqualTo("bar,baz,biz");
}
@@ -86,7 +85,7 @@ public class JOptCommandLinePropertySourceTests {
OptionSet options = parser.parse("--foo=bar", "--foo=baz", "--foo=biz");
CommandLinePropertySource<?> ps = new JOptCommandLinePropertySource(options);
assertEquals(Arrays.asList("bar","baz","biz"), ps.getOptionValues("foo"));
assertThat(ps.getOptionValues("foo")).isEqualTo(Arrays.asList("bar","baz","biz"));
assertThat(ps.getProperty("foo")).isEqualTo("bar,baz,biz");
}

View File

@@ -25,10 +25,6 @@ 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.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* @author Chris Beams
@@ -99,11 +95,11 @@ public class MutablePropertySourcesTests {
assertThat(sources.precedenceOf(PropertySource.named("f"))).isEqualTo(5);
assertThat(sources.precedenceOf(PropertySource.named("g"))).isEqualTo(6);
assertEquals(sources.remove("a"), PropertySource.named("a"));
assertThat(PropertySource.named("a")).isEqualTo(sources.remove("a"));
assertThat(sources.size()).isEqualTo(6);
assertThat(sources.contains("a")).isFalse();
assertNull(sources.remove("a"));
assertThat((Object) sources.remove("a")).isNull();
assertThat(sources.size()).isEqualTo(6);
String bogusPS = "bogus";
@@ -150,19 +146,19 @@ public class MutablePropertySourcesTests {
sources.addLast(new MockPropertySource("test"));
Iterator<PropertySource<?>> it = sources.iterator();
assertTrue(it.hasNext());
assertEquals("test", it.next().getName());
assertThat(it.hasNext()).isTrue();
assertThat(it.next().getName()).isEqualTo("test");
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(
it::remove);
assertFalse(it.hasNext());
assertThat(it.hasNext()).isFalse();
}
@Test
public void iteratorIsEmptyForEmptySources() {
MutablePropertySources sources = new MutablePropertySources();
Iterator<PropertySource<?>> it = sources.iterator();
assertFalse(it.hasNext());
assertThat(it.hasNext()).isFalse();
}
@Test

View File

@@ -25,10 +25,8 @@ import org.junit.Test;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Tests for {@link Profiles}.
@@ -71,63 +69,63 @@ public class ProfilesTests {
@Test
public void ofSingleElement() {
Profiles profiles = Profiles.of("spring");
assertTrue(profiles.matches(activeProfiles("spring")));
assertFalse(profiles.matches(activeProfiles("framework")));
assertThat(profiles.matches(activeProfiles("spring"))).isTrue();
assertThat(profiles.matches(activeProfiles("framework"))).isFalse();
}
@Test
public void ofSingleInvertedElement() {
Profiles profiles = Profiles.of("!spring");
assertFalse(profiles.matches(activeProfiles("spring")));
assertTrue(profiles.matches(activeProfiles("framework")));
assertThat(profiles.matches(activeProfiles("spring"))).isFalse();
assertThat(profiles.matches(activeProfiles("framework"))).isTrue();
}
@Test
public void ofMultipleElements() {
Profiles profiles = Profiles.of("spring", "framework");
assertTrue(profiles.matches(activeProfiles("spring")));
assertTrue(profiles.matches(activeProfiles("framework")));
assertFalse(profiles.matches(activeProfiles("java")));
assertThat(profiles.matches(activeProfiles("spring"))).isTrue();
assertThat(profiles.matches(activeProfiles("framework"))).isTrue();
assertThat(profiles.matches(activeProfiles("java"))).isFalse();
}
@Test
public void ofMultipleElementsWithInverted() {
Profiles profiles = Profiles.of("!spring", "framework");
assertFalse(profiles.matches(activeProfiles("spring")));
assertTrue(profiles.matches(activeProfiles("spring", "framework")));
assertTrue(profiles.matches(activeProfiles("framework")));
assertTrue(profiles.matches(activeProfiles("java")));
assertThat(profiles.matches(activeProfiles("spring"))).isFalse();
assertThat(profiles.matches(activeProfiles("spring", "framework"))).isTrue();
assertThat(profiles.matches(activeProfiles("framework"))).isTrue();
assertThat(profiles.matches(activeProfiles("java"))).isTrue();
}
@Test
public void ofMultipleElementsAllInverted() {
Profiles profiles = Profiles.of("!spring", "!framework");
assertTrue(profiles.matches(activeProfiles("spring")));
assertTrue(profiles.matches(activeProfiles("framework")));
assertTrue(profiles.matches(activeProfiles("java")));
assertFalse(profiles.matches(activeProfiles("spring", "framework")));
assertFalse(profiles.matches(activeProfiles("spring", "framework", "java")));
assertThat(profiles.matches(activeProfiles("spring"))).isTrue();
assertThat(profiles.matches(activeProfiles("framework"))).isTrue();
assertThat(profiles.matches(activeProfiles("java"))).isTrue();
assertThat(profiles.matches(activeProfiles("spring", "framework"))).isFalse();
assertThat(profiles.matches(activeProfiles("spring", "framework", "java"))).isFalse();
}
@Test
public void ofSingleExpression() {
Profiles profiles = Profiles.of("(spring)");
assertTrue(profiles.matches(activeProfiles("spring")));
assertFalse(profiles.matches(activeProfiles("framework")));
assertThat(profiles.matches(activeProfiles("spring"))).isTrue();
assertThat(profiles.matches(activeProfiles("framework"))).isFalse();
}
@Test
public void ofSingleExpressionInverted() {
Profiles profiles = Profiles.of("!(spring)");
assertFalse(profiles.matches(activeProfiles("spring")));
assertTrue(profiles.matches(activeProfiles("framework")));
assertThat(profiles.matches(activeProfiles("spring"))).isFalse();
assertThat(profiles.matches(activeProfiles("framework"))).isTrue();
}
@Test
public void ofSingleInvertedExpression() {
Profiles profiles = Profiles.of("(!spring)");
assertFalse(profiles.matches(activeProfiles("spring")));
assertTrue(profiles.matches(activeProfiles("framework")));
assertThat(profiles.matches(activeProfiles("spring"))).isFalse();
assertThat(profiles.matches(activeProfiles("framework"))).isTrue();
}
@Test
@@ -143,10 +141,10 @@ public class ProfilesTests {
}
private void assertOrExpression(Profiles profiles) {
assertTrue(profiles.matches(activeProfiles("spring")));
assertTrue(profiles.matches(activeProfiles("framework")));
assertTrue(profiles.matches(activeProfiles("spring", "framework")));
assertFalse(profiles.matches(activeProfiles("java")));
assertThat(profiles.matches(activeProfiles("spring"))).isTrue();
assertThat(profiles.matches(activeProfiles("framework"))).isTrue();
assertThat(profiles.matches(activeProfiles("spring", "framework"))).isTrue();
assertThat(profiles.matches(activeProfiles("java"))).isFalse();
}
@Test
@@ -168,10 +166,10 @@ public class ProfilesTests {
}
private void assertAndExpression(Profiles profiles) {
assertFalse(profiles.matches(activeProfiles("spring")));
assertFalse(profiles.matches(activeProfiles("framework")));
assertTrue(profiles.matches(activeProfiles("spring", "framework")));
assertFalse(profiles.matches(activeProfiles("java")));
assertThat(profiles.matches(activeProfiles("spring"))).isFalse();
assertThat(profiles.matches(activeProfiles("framework"))).isFalse();
assertThat(profiles.matches(activeProfiles("spring", "framework"))).isTrue();
assertThat(profiles.matches(activeProfiles("java"))).isFalse();
}
@Test
@@ -187,10 +185,10 @@ public class ProfilesTests {
}
private void assertOfNotAndExpression(Profiles profiles) {
assertTrue(profiles.matches(activeProfiles("spring")));
assertTrue(profiles.matches(activeProfiles("framework")));
assertFalse(profiles.matches(activeProfiles("spring", "framework")));
assertTrue(profiles.matches(activeProfiles("java")));
assertThat(profiles.matches(activeProfiles("spring"))).isTrue();
assertThat(profiles.matches(activeProfiles("framework"))).isTrue();
assertThat(profiles.matches(activeProfiles("spring", "framework"))).isFalse();
assertThat(profiles.matches(activeProfiles("java"))).isTrue();
}
@Test
@@ -224,10 +222,10 @@ public class ProfilesTests {
}
private void assertOfAndExpressionWithInvertedSingleElement(Profiles profiles) {
assertTrue(profiles.matches(activeProfiles("framework")));
assertFalse(profiles.matches(activeProfiles("java")));
assertFalse(profiles.matches(activeProfiles("spring", "framework")));
assertFalse(profiles.matches(activeProfiles("spring")));
assertThat(profiles.matches(activeProfiles("framework"))).isTrue();
assertThat(profiles.matches(activeProfiles("java"))).isFalse();
assertThat(profiles.matches(activeProfiles("spring", "framework"))).isFalse();
assertThat(profiles.matches(activeProfiles("spring"))).isFalse();
}
@Test
@@ -237,10 +235,10 @@ public class ProfilesTests {
}
private void assertOfOrExpressionWithInvertedSingleElement(Profiles profiles) {
assertTrue(profiles.matches(activeProfiles("framework")));
assertTrue(profiles.matches(activeProfiles("java")));
assertTrue(profiles.matches(activeProfiles("spring", "framework")));
assertFalse(profiles.matches(activeProfiles("spring")));
assertThat(profiles.matches(activeProfiles("framework"))).isTrue();
assertThat(profiles.matches(activeProfiles("java"))).isTrue();
assertThat(profiles.matches(activeProfiles("spring", "framework"))).isTrue();
assertThat(profiles.matches(activeProfiles("spring"))).isFalse();
}
@Test
@@ -256,10 +254,10 @@ public class ProfilesTests {
}
private void assertOfNotOrExpression(Profiles profiles) {
assertFalse(profiles.matches(activeProfiles("spring")));
assertFalse(profiles.matches(activeProfiles("framework")));
assertFalse(profiles.matches(activeProfiles("spring", "framework")));
assertTrue(profiles.matches(activeProfiles("java")));
assertThat(profiles.matches(activeProfiles("spring"))).isFalse();
assertThat(profiles.matches(activeProfiles("framework"))).isFalse();
assertThat(profiles.matches(activeProfiles("spring", "framework"))).isFalse();
assertThat(profiles.matches(activeProfiles("java"))).isTrue();
}
@Test
@@ -275,10 +273,10 @@ public class ProfilesTests {
}
private void assertComplexExpression(Profiles profiles) {
assertFalse(profiles.matches(activeProfiles("spring")));
assertTrue(profiles.matches(activeProfiles("spring", "framework")));
assertTrue(profiles.matches(activeProfiles("spring", "java")));
assertFalse(profiles.matches(activeProfiles("java", "framework")));
assertThat(profiles.matches(activeProfiles("spring"))).isFalse();
assertThat(profiles.matches(activeProfiles("spring", "framework"))).isTrue();
assertThat(profiles.matches(activeProfiles("spring", "java"))).isTrue();
assertThat(profiles.matches(activeProfiles("java", "framework"))).isFalse();
}
@Test
@@ -290,8 +288,7 @@ public class ProfilesTests {
@Test
public void sensibleToString() {
assertEquals("spring & framework or java | kotlin",
Profiles.of("spring & framework", "java | kotlin").toString());
assertThat(Profiles.of("spring & framework", "java | kotlin").toString()).isEqualTo("spring & framework or java | kotlin");
}
private void assertMalformed(Supplier<Profiles> supplier) {

View File

@@ -30,8 +30,6 @@ 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.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.springframework.core.env.AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME;
import static org.springframework.core.env.AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME;
import static org.springframework.core.env.AbstractEnvironment.RESERVED_DEFAULT_PROFILE_NAME;
@@ -377,21 +375,21 @@ public class StandardEnvironmentTests {
@Test
public void suppressGetenvAccessThroughSystemProperty() {
System.setProperty("spring.getenv.ignore", "true");
assertTrue(environment.getSystemEnvironment().isEmpty());
assertThat(environment.getSystemEnvironment().isEmpty()).isTrue();
System.clearProperty("spring.getenv.ignore");
}
@Test
public void suppressGetenvAccessThroughSpringProperty() {
SpringProperties.setProperty("spring.getenv.ignore", "true");
assertTrue(environment.getSystemEnvironment().isEmpty());
assertThat(environment.getSystemEnvironment().isEmpty()).isTrue();
SpringProperties.setProperty("spring.getenv.ignore", null);
}
@Test
public void suppressGetenvAccessThroughSpringFlag() {
SpringProperties.setFlag("spring.getenv.ignore");
assertTrue(environment.getSystemEnvironment().isEmpty());
assertThat(environment.getSystemEnvironment().isEmpty()).isTrue();
SpringProperties.setProperty("spring.getenv.ignore", null);
}
@@ -405,7 +403,7 @@ public class StandardEnvironmentTests {
{
Map<?, ?> systemProperties = environment.getSystemProperties();
assertThat(systemProperties).isNotNull();
assertSame(systemProperties, System.getProperties());
assertThat(System.getProperties()).isSameAs(systemProperties);
assertThat(systemProperties.get(ALLOWED_PROPERTY_NAME)).isEqualTo(ALLOWED_PROPERTY_VALUE);
assertThat(systemProperties.get(DISALLOWED_PROPERTY_NAME)).isEqualTo(DISALLOWED_PROPERTY_VALUE);
@@ -473,7 +471,7 @@ public class StandardEnvironmentTests {
{
Map<String, Object> systemEnvironment = environment.getSystemEnvironment();
assertThat(systemEnvironment).isNotNull();
assertSame(systemEnvironment, System.getenv());
assertThat(System.getenv()).isSameAs(systemEnvironment);
}
SecurityManager oldSecurityManager = System.getSecurityManager();

View File

@@ -59,7 +59,7 @@ public class SystemEnvironmentPropertySourceTests {
envMap.put("akey", "avalue");
assertThat(ps.containsProperty("akey")).isEqualTo(true);
assertThat(ps.getProperty("akey")).isEqualTo((Object)"avalue");
assertThat(ps.getProperty("akey")).isEqualTo("avalue");
}
@Test
@@ -67,7 +67,7 @@ public class SystemEnvironmentPropertySourceTests {
envMap.put("a.key", "a.value");
assertThat(ps.containsProperty("a.key")).isEqualTo(true);
assertThat(ps.getProperty("a.key")).isEqualTo((Object)"a.value");
assertThat(ps.getProperty("a.key")).isEqualTo("a.value");
}
@Test
@@ -77,8 +77,8 @@ public class SystemEnvironmentPropertySourceTests {
assertThat(ps.containsProperty("a_key")).isEqualTo(true);
assertThat(ps.containsProperty("a.key")).isEqualTo(true);
assertThat(ps.getProperty("a_key")).isEqualTo((Object)"a_value");
assertThat( ps.getProperty("a.key")).isEqualTo((Object)"a_value");
assertThat(ps.getProperty("a_key")).isEqualTo("a_value");
assertThat( ps.getProperty("a.key")).isEqualTo("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")).isEqualTo((Object)"a_value");
assertThat( ps.getProperty("a.key")).isEqualTo((Object)"a.value");
assertThat(ps.getProperty("a_key")).isEqualTo("a_value");
assertThat( ps.getProperty("a.key")).isEqualTo("a.value");
}
@Test
@@ -171,7 +171,7 @@ public class SystemEnvironmentPropertySourceTests {
};
assertThat(ps.containsProperty("A_KEY")).isEqualTo(true);
assertThat(ps.getProperty("A_KEY")).isEqualTo((Object)"a_value");
assertThat(ps.getProperty("A_KEY")).isEqualTo("a_value");
}
}

View File

@@ -22,10 +22,8 @@ import java.util.regex.Pattern;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Unit tests that serve as regression tests for the bugs described in SPR-6888
@@ -100,35 +98,35 @@ public class ClassPathResourceTests {
@Test
public void dropLeadingSlashForClassLoaderAccess() {
assertEquals("test.html", new ClassPathResource("/test.html").getPath());
assertEquals("test.html", ((ClassPathResource) new ClassPathResource("").createRelative("/test.html")).getPath());
assertThat(new ClassPathResource("/test.html").getPath()).isEqualTo("test.html");
assertThat(((ClassPathResource) new ClassPathResource("").createRelative("/test.html")).getPath()).isEqualTo("test.html");
}
@Test
public void preserveLeadingSlashForClassRelativeAccess() {
assertEquals("/test.html", new ClassPathResource("/test.html", getClass()).getPath());
assertEquals("/test.html", ((ClassPathResource) new ClassPathResource("", getClass()).createRelative("/test.html")).getPath());
assertThat(new ClassPathResource("/test.html", getClass()).getPath()).isEqualTo("/test.html");
assertThat(((ClassPathResource) new ClassPathResource("", getClass()).createRelative("/test.html")).getPath()).isEqualTo("/test.html");
}
@Test
public void directoryNotReadable() {
Resource fileDir = new ClassPathResource("org/springframework/core");
assertTrue(fileDir.exists());
assertFalse(fileDir.isReadable());
assertThat(fileDir.exists()).isTrue();
assertThat(fileDir.isReadable()).isFalse();
Resource jarDir = new ClassPathResource("reactor/core");
assertTrue(jarDir.exists());
assertFalse(jarDir.isReadable());
assertThat(jarDir.exists()).isTrue();
assertThat(jarDir.isReadable()).isFalse();
}
private void assertDescriptionContainsExpectedPath(ClassPathResource resource, String expectedPath) {
Matcher matcher = DESCRIPTION_PATTERN.matcher(resource.getDescription());
assertTrue(matcher.matches());
assertEquals(1, matcher.groupCount());
assertThat(matcher.matches()).isTrue();
assertThat(matcher.groupCount()).isEqualTo(1);
String match = matcher.group(1);
assertEquals(expectedPath, match);
assertThat(match).isEqualTo(expectedPath);
}
private void assertExceptionContainsFullyQualifiedPath(ClassPathResource resource) {

View File

@@ -22,10 +22,8 @@ import org.junit.Test;
import org.springframework.core.env.StandardEnvironment;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for the {@link ResourceEditor} class.
@@ -41,8 +39,8 @@ public class ResourceEditorTests {
PropertyEditor editor = new ResourceEditor();
editor.setAsText("classpath:org/springframework/core/io/ResourceEditorTests.class");
Resource resource = (Resource) editor.getValue();
assertNotNull(resource);
assertTrue(resource.exists());
assertThat(resource).isNotNull();
assertThat(resource.exists()).isTrue();
}
@Test
@@ -55,14 +53,14 @@ public class ResourceEditorTests {
public void setAndGetAsTextWithNull() {
PropertyEditor editor = new ResourceEditor();
editor.setAsText(null);
assertEquals("", editor.getAsText());
assertThat(editor.getAsText()).isEqualTo("");
}
@Test
public void setAndGetAsTextWithWhitespaceResource() {
PropertyEditor editor = new ResourceEditor();
editor.setAsText(" ");
assertEquals("", editor.getAsText());
assertThat(editor.getAsText()).isEqualTo("");
}
@Test
@@ -72,7 +70,7 @@ public class ResourceEditorTests {
try {
editor.setAsText("${test.prop}");
Resource resolved = (Resource) editor.getValue();
assertEquals("foo", resolved.getFilename());
assertThat(resolved.getFilename()).isEqualTo("foo");
}
finally {
System.getProperties().remove("test.prop");
@@ -86,7 +84,7 @@ public class ResourceEditorTests {
try {
editor.setAsText("${test.prop}-${bar}");
Resource resolved = (Resource) editor.getValue();
assertEquals("foo-${bar}", resolved.getFilename());
assertThat(resolved.getFilename()).isEqualTo("foo-${bar}");
}
finally {
System.getProperties().remove("test.prop");

View File

@@ -34,9 +34,6 @@ import org.springframework.util.FileCopyUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for various {@link Resource} implementations.
@@ -51,45 +48,45 @@ public class ResourceTests {
@Test
public void testByteArrayResource() throws IOException {
Resource resource = new ByteArrayResource("testString".getBytes());
assertTrue(resource.exists());
assertFalse(resource.isOpen());
assertThat(resource.exists()).isTrue();
assertThat(resource.isOpen()).isFalse();
String content = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream()));
assertEquals("testString", content);
assertEquals(resource, new ByteArrayResource("testString".getBytes()));
assertThat(content).isEqualTo("testString");
assertThat(new ByteArrayResource("testString".getBytes())).isEqualTo(resource);
}
@Test
public void testByteArrayResourceWithDescription() throws IOException {
Resource resource = new ByteArrayResource("testString".getBytes(), "my description");
assertTrue(resource.exists());
assertFalse(resource.isOpen());
assertThat(resource.exists()).isTrue();
assertThat(resource.isOpen()).isFalse();
String content = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream()));
assertEquals("testString", content);
assertTrue(resource.getDescription().contains("my description"));
assertEquals(resource, new ByteArrayResource("testString".getBytes()));
assertThat(content).isEqualTo("testString");
assertThat(resource.getDescription().contains("my description")).isTrue();
assertThat(new ByteArrayResource("testString".getBytes())).isEqualTo(resource);
}
@Test
public void testInputStreamResource() throws IOException {
InputStream is = new ByteArrayInputStream("testString".getBytes());
Resource resource = new InputStreamResource(is);
assertTrue(resource.exists());
assertTrue(resource.isOpen());
assertThat(resource.exists()).isTrue();
assertThat(resource.isOpen()).isTrue();
String content = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream()));
assertEquals("testString", content);
assertEquals(resource, new InputStreamResource(is));
assertThat(content).isEqualTo("testString");
assertThat(new InputStreamResource(is)).isEqualTo(resource);
}
@Test
public void testInputStreamResourceWithDescription() throws IOException {
InputStream is = new ByteArrayInputStream("testString".getBytes());
Resource resource = new InputStreamResource(is, "my description");
assertTrue(resource.exists());
assertTrue(resource.isOpen());
assertThat(resource.exists()).isTrue();
assertThat(resource.isOpen()).isTrue();
String content = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream()));
assertEquals("testString", content);
assertTrue(resource.getDescription().contains("my description"));
assertEquals(resource, new InputStreamResource(is));
assertThat(content).isEqualTo("testString");
assertThat(resource.getDescription().contains("my description")).isTrue();
assertThat(new InputStreamResource(is)).isEqualTo(resource);
}
@Test
@@ -97,15 +94,15 @@ public class ResourceTests {
Resource resource = new ClassPathResource("org/springframework/core/io/Resource.class");
doTestResource(resource);
Resource resource2 = new ClassPathResource("org/springframework/core/../core/io/./Resource.class");
assertEquals(resource, resource2);
assertThat(resource2).isEqualTo(resource);
Resource resource3 = new ClassPathResource("org/springframework/core/").createRelative("../core/io/./Resource.class");
assertEquals(resource, resource3);
assertThat(resource3).isEqualTo(resource);
// Check whether equal/hashCode works in a HashSet.
HashSet<Resource> resources = new HashSet<>();
resources.add(resource);
resources.add(resource2);
assertEquals(1, resources.size());
assertThat(resources.size()).isEqualTo(1);
}
@Test
@@ -113,15 +110,14 @@ public class ResourceTests {
Resource resource =
new ClassPathResource("org/springframework/core/io/Resource.class", getClass().getClassLoader());
doTestResource(resource);
assertEquals(resource,
new ClassPathResource("org/springframework/core/../core/io/./Resource.class", getClass().getClassLoader()));
assertThat(new ClassPathResource("org/springframework/core/../core/io/./Resource.class", getClass().getClassLoader())).isEqualTo(resource);
}
@Test
public void testClassPathResourceWithClass() throws IOException {
Resource resource = new ClassPathResource("Resource.class", getClass());
doTestResource(resource);
assertEquals(resource, new ClassPathResource("Resource.class", getClass()));
assertThat(new ClassPathResource("Resource.class", getClass())).isEqualTo(resource);
}
@Test
@@ -129,7 +125,7 @@ public class ResourceTests {
String file = getClass().getResource("Resource.class").getFile();
Resource resource = new FileSystemResource(file);
doTestResource(resource);
assertEquals(new FileSystemResource(file), resource);
assertThat(resource).isEqualTo(new FileSystemResource(file));
}
@Test
@@ -137,64 +133,64 @@ public class ResourceTests {
Path filePath = Paths.get(getClass().getResource("Resource.class").toURI());
Resource resource = new FileSystemResource(filePath);
doTestResource(resource);
assertEquals(new FileSystemResource(filePath), resource);
assertThat(resource).isEqualTo(new FileSystemResource(filePath));
}
@Test
public void testFileSystemResourceWithPlainPath() {
Resource resource = new FileSystemResource("core/io/Resource.class");
assertEquals(resource, new FileSystemResource("core/../core/io/./Resource.class"));
assertThat(new FileSystemResource("core/../core/io/./Resource.class")).isEqualTo(resource);
}
@Test
public void testUrlResource() throws IOException {
Resource resource = new UrlResource(getClass().getResource("Resource.class"));
doTestResource(resource);
assertEquals(new UrlResource(getClass().getResource("Resource.class")), resource);
assertThat(resource).isEqualTo(new UrlResource(getClass().getResource("Resource.class")));
Resource resource2 = new UrlResource("file:core/io/Resource.class");
assertEquals(resource2, new UrlResource("file:core/../core/io/./Resource.class"));
assertThat(new UrlResource("file:core/../core/io/./Resource.class")).isEqualTo(resource2);
assertEquals("test.txt", new UrlResource("file:/dir/test.txt?argh").getFilename());
assertEquals("test.txt", new UrlResource("file:\\dir\\test.txt?argh").getFilename());
assertEquals("test.txt", new UrlResource("file:\\dir/test.txt?argh").getFilename());
assertThat(new UrlResource("file:/dir/test.txt?argh").getFilename()).isEqualTo("test.txt");
assertThat(new UrlResource("file:\\dir\\test.txt?argh").getFilename()).isEqualTo("test.txt");
assertThat(new UrlResource("file:\\dir/test.txt?argh").getFilename()).isEqualTo("test.txt");
}
private void doTestResource(Resource resource) throws IOException {
assertEquals("Resource.class", resource.getFilename());
assertTrue(resource.getURL().getFile().endsWith("Resource.class"));
assertTrue(resource.exists());
assertTrue(resource.isReadable());
assertTrue(resource.contentLength() > 0);
assertTrue(resource.lastModified() > 0);
assertThat(resource.getFilename()).isEqualTo("Resource.class");
assertThat(resource.getURL().getFile().endsWith("Resource.class")).isTrue();
assertThat(resource.exists()).isTrue();
assertThat(resource.isReadable()).isTrue();
assertThat(resource.contentLength() > 0).isTrue();
assertThat(resource.lastModified() > 0).isTrue();
Resource relative1 = resource.createRelative("ClassPathResource.class");
assertEquals("ClassPathResource.class", relative1.getFilename());
assertTrue(relative1.getURL().getFile().endsWith("ClassPathResource.class"));
assertTrue(relative1.exists());
assertTrue(relative1.isReadable());
assertTrue(relative1.contentLength() > 0);
assertTrue(relative1.lastModified() > 0);
assertThat(relative1.getFilename()).isEqualTo("ClassPathResource.class");
assertThat(relative1.getURL().getFile().endsWith("ClassPathResource.class")).isTrue();
assertThat(relative1.exists()).isTrue();
assertThat(relative1.isReadable()).isTrue();
assertThat(relative1.contentLength() > 0).isTrue();
assertThat(relative1.lastModified() > 0).isTrue();
Resource relative2 = resource.createRelative("support/ResourcePatternResolver.class");
assertEquals("ResourcePatternResolver.class", relative2.getFilename());
assertTrue(relative2.getURL().getFile().endsWith("ResourcePatternResolver.class"));
assertTrue(relative2.exists());
assertTrue(relative2.isReadable());
assertTrue(relative2.contentLength() > 0);
assertTrue(relative2.lastModified() > 0);
assertThat(relative2.getFilename()).isEqualTo("ResourcePatternResolver.class");
assertThat(relative2.getURL().getFile().endsWith("ResourcePatternResolver.class")).isTrue();
assertThat(relative2.exists()).isTrue();
assertThat(relative2.isReadable()).isTrue();
assertThat(relative2.contentLength() > 0).isTrue();
assertThat(relative2.lastModified() > 0).isTrue();
Resource relative3 = resource.createRelative("../SpringVersion.class");
assertEquals("SpringVersion.class", relative3.getFilename());
assertTrue(relative3.getURL().getFile().endsWith("SpringVersion.class"));
assertTrue(relative3.exists());
assertTrue(relative3.isReadable());
assertTrue(relative3.contentLength() > 0);
assertTrue(relative3.lastModified() > 0);
assertThat(relative3.getFilename()).isEqualTo("SpringVersion.class");
assertThat(relative3.getURL().getFile().endsWith("SpringVersion.class")).isTrue();
assertThat(relative3.exists()).isTrue();
assertThat(relative3.isReadable()).isTrue();
assertThat(relative3.contentLength() > 0).isTrue();
assertThat(relative3.lastModified() > 0).isTrue();
Resource relative4 = resource.createRelative("X.class");
assertFalse(relative4.exists());
assertFalse(relative4.isReadable());
assertThat(relative4.exists()).isFalse();
assertThat(relative4.isReadable()).isFalse();
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(
relative4::contentLength);
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(
@@ -205,27 +201,27 @@ public class ResourceTests {
public void testClassPathResourceWithRelativePath() throws IOException {
Resource resource = new ClassPathResource("dir/");
Resource relative = resource.createRelative("subdir");
assertEquals(new ClassPathResource("dir/subdir"), relative);
assertThat(relative).isEqualTo(new ClassPathResource("dir/subdir"));
}
@Test
public void testFileSystemResourceWithRelativePath() throws IOException {
Resource resource = new FileSystemResource("dir/");
Resource relative = resource.createRelative("subdir");
assertEquals(new FileSystemResource("dir/subdir"), relative);
assertThat(relative).isEqualTo(new FileSystemResource("dir/subdir"));
}
@Test
public void testUrlResourceWithRelativePath() throws IOException {
Resource resource = new UrlResource("file:dir/");
Resource relative = resource.createRelative("subdir");
assertEquals(new UrlResource("file:dir/subdir"), relative);
assertThat(relative).isEqualTo(new UrlResource("file:dir/subdir"));
}
@Ignore @Test // this test is quite slow. TODO: re-enable with JUnit categories
public void testNonFileResourceExists() throws Exception {
Resource resource = new UrlResource("https://www.springframework.org");
assertTrue(resource.exists());
assertThat(resource.exists()).isTrue();
}
@Test
@@ -280,7 +276,7 @@ public class ResourceTests {
ByteBuffer buffer = ByteBuffer.allocate((int) resource.contentLength());
channel.read(buffer);
buffer.rewind();
assertTrue(buffer.limit() > 0);
assertThat(buffer.limit() > 0).isTrue();
}
finally {
if (channel != null) {

View File

@@ -36,7 +36,7 @@ import reactor.core.publisher.Mono;
import org.springframework.core.io.buffer.support.DataBufferTestUtils;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Base class for tests that read or write data buffers with a rule to check
@@ -96,7 +96,7 @@ public abstract class AbstractDataBufferAllocatingTestCase {
String value =
DataBufferTestUtils.dumpString(dataBuffer, StandardCharsets.UTF_8);
DataBufferUtils.release(dataBuffer);
assertEquals(expected, value);
assertThat(value).isEqualTo(expected);
};
}
@@ -139,7 +139,7 @@ public abstract class AbstractDataBufferAllocatingTestCase {
}
continue;
}
assertEquals("ByteBuf Leak: " + total + " unreleased allocations", 0, total);
assertThat(total).as("ByteBuf Leak: " + total + " unreleased allocations").isEqualTo(0);
}
}
}

View File

@@ -25,11 +25,9 @@ import java.util.Arrays;
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.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Arjen Poutsma
@@ -40,39 +38,39 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
public void byteCountsAndPositions() {
DataBuffer buffer = createDataBuffer(2);
assertEquals(0, buffer.readPosition());
assertEquals(0, buffer.writePosition());
assertEquals(0, buffer.readableByteCount());
assertEquals(2, buffer.writableByteCount());
assertEquals(2, buffer.capacity());
assertThat(buffer.readPosition()).isEqualTo(0);
assertThat(buffer.writePosition()).isEqualTo(0);
assertThat(buffer.readableByteCount()).isEqualTo(0);
assertThat(buffer.writableByteCount()).isEqualTo(2);
assertThat(buffer.capacity()).isEqualTo(2);
buffer.write((byte) 'a');
assertEquals(0, buffer.readPosition());
assertEquals(1, buffer.writePosition());
assertEquals(1, buffer.readableByteCount());
assertEquals(1, buffer.writableByteCount());
assertEquals(2, buffer.capacity());
assertThat(buffer.readPosition()).isEqualTo(0);
assertThat(buffer.writePosition()).isEqualTo(1);
assertThat(buffer.readableByteCount()).isEqualTo(1);
assertThat(buffer.writableByteCount()).isEqualTo(1);
assertThat(buffer.capacity()).isEqualTo(2);
buffer.write((byte) 'b');
assertEquals(0, buffer.readPosition());
assertEquals(2, buffer.writePosition());
assertEquals(2, buffer.readableByteCount());
assertEquals(0, buffer.writableByteCount());
assertEquals(2, buffer.capacity());
assertThat(buffer.readPosition()).isEqualTo(0);
assertThat(buffer.writePosition()).isEqualTo(2);
assertThat(buffer.readableByteCount()).isEqualTo(2);
assertThat(buffer.writableByteCount()).isEqualTo(0);
assertThat(buffer.capacity()).isEqualTo(2);
buffer.read();
assertEquals(1, buffer.readPosition());
assertEquals(2, buffer.writePosition());
assertEquals(1, buffer.readableByteCount());
assertEquals(0, buffer.writableByteCount());
assertEquals(2, buffer.capacity());
assertThat(buffer.readPosition()).isEqualTo(1);
assertThat(buffer.writePosition()).isEqualTo(2);
assertThat(buffer.readableByteCount()).isEqualTo(1);
assertThat(buffer.writableByteCount()).isEqualTo(0);
assertThat(buffer.capacity()).isEqualTo(2);
buffer.read();
assertEquals(2, buffer.readPosition());
assertEquals(2, buffer.writePosition());
assertEquals(0, buffer.readableByteCount());
assertEquals(0, buffer.writableByteCount());
assertEquals(2, buffer.capacity());
assertThat(buffer.readPosition()).isEqualTo(2);
assertThat(buffer.writePosition()).isEqualTo(2);
assertThat(buffer.readableByteCount()).isEqualTo(0);
assertThat(buffer.writableByteCount()).isEqualTo(0);
assertThat(buffer.capacity()).isEqualTo(2);
release(buffer);
}
@@ -133,7 +131,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
buffer.write(new byte[]{'a', 'b', 'c'});
int ch = buffer.read();
assertEquals('a', ch);
assertThat(ch).isEqualTo((byte) 'a');
buffer.write((byte) 'd');
buffer.write((byte) 'e');
@@ -141,7 +139,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
byte[] result = new byte[4];
buffer.read(result);
assertArrayEquals(new byte[]{'b', 'c', 'd', 'e'}, result);
assertThat(result).isEqualTo(new byte[]{'b', 'c', 'd', 'e'});
release(buffer);
}
@@ -175,7 +173,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
DataBuffer buffer = createDataBuffer(1);
buffer.write("", StandardCharsets.UTF_8);
assertEquals(0, buffer.readableByteCount());
assertThat(buffer.readableByteCount()).isEqualTo(0);
release(buffer);
}
@@ -188,7 +186,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
byte[] result = new byte[6];
buffer.read(result);
assertArrayEquals("Spring".getBytes(StandardCharsets.UTF_8), result);
assertThat(result).isEqualTo("Spring".getBytes(StandardCharsets.UTF_8));
release(buffer);
}
@@ -200,7 +198,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
byte[] result = new byte[10];
buffer.read(result);
assertArrayEquals("Spring €".getBytes(StandardCharsets.UTF_8), result);
assertThat(result).isEqualTo("Spring €".getBytes(StandardCharsets.UTF_8));
release(buffer);
}
@@ -212,7 +210,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
byte[] result = new byte[1];
buffer.read(result);
assertArrayEquals("\u00A3".getBytes(StandardCharsets.ISO_8859_1), result);
assertThat(result).isEqualTo("\u00A3".getBytes(StandardCharsets.ISO_8859_1));
release(buffer);
}
@@ -221,18 +219,18 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
DataBuffer buffer = createDataBuffer(1);
buffer.write("abc", StandardCharsets.UTF_8);
assertEquals(3, buffer.readableByteCount());
assertThat(buffer.readableByteCount()).isEqualTo(3);
buffer.write("def", StandardCharsets.UTF_8);
assertEquals(6, buffer.readableByteCount());
assertThat(buffer.readableByteCount()).isEqualTo(6);
buffer.write("ghi", StandardCharsets.UTF_8);
assertEquals(9, buffer.readableByteCount());
assertThat(buffer.readableByteCount()).isEqualTo(9);
byte[] result = new byte[9];
buffer.read(result);
assertArrayEquals("abcdefghi".getBytes(), result);
assertThat(result).isEqualTo("abcdefghi".getBytes());
release(buffer);
}
@@ -245,26 +243,26 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
InputStream inputStream = buffer.asInputStream();
assertEquals(4, inputStream.available());
assertThat(inputStream.available()).isEqualTo(4);
int result = inputStream.read();
assertEquals('b', result);
assertEquals(3, inputStream.available());
assertThat(result).isEqualTo((byte) 'b');
assertThat(inputStream.available()).isEqualTo(3);
byte[] bytes = new byte[2];
int len = inputStream.read(bytes);
assertEquals(2, len);
assertArrayEquals(new byte[]{'c', 'd'}, bytes);
assertEquals(1, inputStream.available());
assertThat(len).isEqualTo(2);
assertThat(bytes).isEqualTo(new byte[]{'c', 'd'});
assertThat(inputStream.available()).isEqualTo(1);
Arrays.fill(bytes, (byte) 0);
len = inputStream.read(bytes);
assertEquals(1, len);
assertArrayEquals(new byte[]{'e', (byte) 0}, bytes);
assertEquals(0, inputStream.available());
assertThat(len).isEqualTo(1);
assertThat(bytes).isEqualTo(new byte[]{'e', (byte) 0});
assertThat(inputStream.available()).isEqualTo(0);
assertEquals(-1, inputStream.read());
assertEquals(-1, inputStream.read(bytes));
assertThat(inputStream.read()).isEqualTo(-1);
assertThat(inputStream.read(bytes)).isEqualTo(-1);
release(buffer);
}
@@ -280,8 +278,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
try {
byte[] result = new byte[3];
int len = inputStream.read(result);
assertEquals(3, len);
assertArrayEquals(bytes, result);
assertThat(len).isEqualTo(3);
assertThat(result).isEqualTo(bytes);
}
finally {
inputStream.close();
@@ -304,7 +302,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
byte[] bytes = new byte[5];
buffer.read(bytes);
assertArrayEquals(new byte[]{'a', 'b', 'c', 'd', 'e'}, bytes);
assertThat(bytes).isEqualTo(new byte[]{'a', 'b', 'c', 'd', 'e'});
release(buffer);
}
@@ -313,10 +311,10 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
public void expand() {
DataBuffer buffer = createDataBuffer(1);
buffer.write((byte) 'a');
assertEquals(1, buffer.capacity());
assertThat(buffer.capacity()).isEqualTo(1);
buffer.write((byte) 'b');
assertTrue(buffer.capacity() > 1);
assertThat(buffer.capacity() > 1).isTrue();
release(buffer);
}
@@ -324,10 +322,10 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
@Test
public void increaseCapacity() {
DataBuffer buffer = createDataBuffer(1);
assertEquals(1, buffer.capacity());
assertThat(buffer.capacity()).isEqualTo(1);
buffer.capacity(2);
assertEquals(2, buffer.capacity());
assertThat(buffer.capacity()).isEqualTo(2);
release(buffer);
}
@@ -337,7 +335,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
DataBuffer buffer = createDataBuffer(2);
buffer.writePosition(2);
buffer.capacity(1);
assertEquals(1, buffer.capacity());
assertThat(buffer.capacity()).isEqualTo(1);
release(buffer);
}
@@ -348,7 +346,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
buffer.writePosition(2);
buffer.readPosition(2);
buffer.capacity(1);
assertEquals(1, buffer.capacity());
assertThat(buffer.capacity()).isEqualTo(1);
release(buffer);
}
@@ -379,11 +377,11 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
buffer1.write(buffer2, buffer3);
buffer1.write((byte) 'd'); // make sure the write index is correctly set
assertEquals(4, buffer1.readableByteCount());
assertThat(buffer1.readableByteCount()).isEqualTo(4);
byte[] result = new byte[4];
buffer1.read(result);
assertArrayEquals(new byte[]{'a', 'b', 'c', 'd'}, result);
assertThat(result).isEqualTo(new byte[]{'a', 'b', 'c', 'd'});
release(buffer1);
}
@@ -404,11 +402,11 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
buffer1.write(buffer2, buffer3);
buffer1.write((byte) 'd'); // make sure the write index is correctly set
assertEquals(4, buffer1.readableByteCount());
assertThat(buffer1.readableByteCount()).isEqualTo(4);
byte[] result = new byte[4];
buffer1.read(result);
assertArrayEquals(new byte[]{'a', 'b', 'c', 'd'}, result);
assertThat(result).isEqualTo(new byte[]{'a', 'b', 'c', 'd'});
release(buffer1, buffer2, buffer3);
}
@@ -420,14 +418,14 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
buffer.read(); // skip a
ByteBuffer result = buffer.asByteBuffer();
assertEquals(2, result.capacity());
assertThat(result.capacity()).isEqualTo(2);
buffer.write((byte) 'd');
assertEquals(2, result.remaining());
assertThat(result.remaining()).isEqualTo(2);
byte[] resultBytes = new byte[2];
result.get(resultBytes);
assertArrayEquals(new byte[]{'b', 'c'}, resultBytes);
assertThat(resultBytes).isEqualTo(new byte[]{'b', 'c'});
release(buffer);
}
@@ -438,14 +436,14 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
buffer.write(new byte[]{'a', 'b'});
ByteBuffer result = buffer.asByteBuffer(1, 2);
assertEquals(2, result.capacity());
assertThat(result.capacity()).isEqualTo(2);
buffer.write((byte) 'c');
assertEquals(2, result.remaining());
assertThat(result.remaining()).isEqualTo(2);
byte[] resultBytes = new byte[2];
result.get(resultBytes);
assertArrayEquals(new byte[]{'b', 'c'}, resultBytes);
assertThat(resultBytes).isEqualTo(new byte[]{'b', 'c'});
release(buffer);
}
@@ -457,9 +455,9 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
dataBuffer.write((byte) 'a');
assertEquals(1, byteBuffer.limit());
assertThat(byteBuffer.limit()).isEqualTo(1);
byte b = byteBuffer.get();
assertEquals('a', b);
assertThat(b).isEqualTo((byte) 'a');
release(dataBuffer);
}
@@ -473,7 +471,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
dataBuffer.writePosition(1);
byte b = dataBuffer.read();
assertEquals('a', b);
assertThat(b).isEqualTo((byte) 'a');
release(dataBuffer);
}
@@ -483,7 +481,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
DataBuffer buffer = createDataBuffer(1);
ByteBuffer result = buffer.asByteBuffer();
assertEquals(0, result.capacity());
assertThat(result.capacity()).isEqualTo(0);
release(buffer);
}
@@ -494,16 +492,16 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
buffer.write(new byte[]{'a', 'b', 'c'});
int result = buffer.indexOf(b -> b == 'c', 0);
assertEquals(2, result);
assertThat(result).isEqualTo(2);
result = buffer.indexOf(b -> b == 'c', Integer.MIN_VALUE);
assertEquals(2, result);
assertThat(result).isEqualTo(2);
result = buffer.indexOf(b -> b == 'c', Integer.MAX_VALUE);
assertEquals(-1, result);
assertThat(result).isEqualTo(-1);
result = buffer.indexOf(b -> b == 'z', 0);
assertEquals(-1, result);
assertThat(result).isEqualTo(-1);
release(buffer);
}
@@ -514,25 +512,25 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
buffer.write(new byte[]{'a', 'b', 'c'});
int result = buffer.lastIndexOf(b -> b == 'b', 2);
assertEquals(1, result);
assertThat(result).isEqualTo(1);
result = buffer.lastIndexOf(b -> b == 'c', 2);
assertEquals(2, result);
assertThat(result).isEqualTo(2);
result = buffer.lastIndexOf(b -> b == 'b', Integer.MAX_VALUE);
assertEquals(1, result);
assertThat(result).isEqualTo(1);
result = buffer.lastIndexOf(b -> b == 'c', Integer.MAX_VALUE);
assertEquals(2, result);
assertThat(result).isEqualTo(2);
result = buffer.lastIndexOf(b -> b == 'b', Integer.MIN_VALUE);
assertEquals(-1, result);
assertThat(result).isEqualTo(-1);
result = buffer.lastIndexOf(b -> b == 'c', Integer.MIN_VALUE);
assertEquals(-1, result);
assertThat(result).isEqualTo(-1);
result = buffer.lastIndexOf(b -> b == 'z', 0);
assertEquals(-1, result);
assertThat(result).isEqualTo(-1);
release(buffer);
}
@@ -543,22 +541,22 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
buffer.write(new byte[]{'a', 'b'});
DataBuffer slice = buffer.slice(1, 2);
assertEquals(2, slice.readableByteCount());
assertThat(slice.readableByteCount()).isEqualTo(2);
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
slice.write((byte) 0));
buffer.write((byte) 'c');
assertEquals(3, buffer.readableByteCount());
assertThat(buffer.readableByteCount()).isEqualTo(3);
byte[] result = new byte[3];
buffer.read(result);
assertArrayEquals(new byte[]{'a', 'b', 'c'}, result);
assertThat(result).isEqualTo(new byte[]{'a', 'b', 'c'});
assertEquals(2, slice.readableByteCount());
assertThat(slice.readableByteCount()).isEqualTo(2);
result = new byte[2];
slice.read(result);
assertArrayEquals(new byte[]{'b', 'c'}, result);
assertThat(result).isEqualTo(new byte[]{'b', 'c'});
release(buffer);
@@ -570,22 +568,22 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
buffer.write(new byte[]{'a', 'b'});
DataBuffer slice = buffer.retainedSlice(1, 2);
assertEquals(2, slice.readableByteCount());
assertThat(slice.readableByteCount()).isEqualTo(2);
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
slice.write((byte) 0));
buffer.write((byte) 'c');
assertEquals(3, buffer.readableByteCount());
assertThat(buffer.readableByteCount()).isEqualTo(3);
byte[] result = new byte[3];
buffer.read(result);
assertArrayEquals(new byte[]{'a', 'b', 'c'}, result);
assertThat(result).isEqualTo(new byte[]{'a', 'b', 'c'});
assertEquals(2, slice.readableByteCount());
assertThat(slice.readableByteCount()).isEqualTo(2);
result = new byte[2];
slice.read(result);
assertArrayEquals(new byte[]{'b', 'c'}, result);
assertThat(result).isEqualTo(new byte[]{'b', 'c'});
release(buffer, slice);
@@ -600,11 +598,11 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
buffer.writePosition(3);
buffer.write(slice);
assertEquals(6, buffer.readableByteCount());
assertThat(buffer.readableByteCount()).isEqualTo(6);
byte[] result = new byte[6];
buffer.read(result);
assertArrayEquals(bytes, result);
assertThat(result).isEqualTo(bytes);
release(buffer);
}
@@ -613,11 +611,11 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
public void join() {
DataBuffer composite = this.bufferFactory.join(Arrays.asList(stringBuffer("a"),
stringBuffer("b"), stringBuffer("c")));
assertEquals(3, composite.readableByteCount());
assertThat(composite.readableByteCount()).isEqualTo(3);
byte[] bytes = new byte[3];
composite.read(bytes);
assertArrayEquals(new byte[] {'a','b','c'}, bytes);
assertThat(bytes).isEqualTo(new byte[] {'a','b','c'});
release(composite);
}
@@ -626,9 +624,9 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
public void getByte() {
DataBuffer buffer = stringBuffer("abc");
assertEquals('a', buffer.getByte(0));
assertEquals('b', buffer.getByte(1));
assertEquals('c', buffer.getByte(2));
assertThat(buffer.getByte(0)).isEqualTo((byte) 'a');
assertThat(buffer.getByte(1)).isEqualTo((byte) 'b');
assertThat(buffer.getByte(2)).isEqualTo((byte) 'c');
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() ->
buffer.getByte(-1));

View File

@@ -48,7 +48,7 @@ import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.buffer.support.DataBufferTestUtils;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.isA;
@@ -155,7 +155,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
byteBuffer.put("foo".getBytes(StandardCharsets.UTF_8));
byteBuffer.flip();
long pos = invocation.getArgument(1);
assertEquals(0, pos);
assertThat(pos).isEqualTo(0);
DataBuffer dataBuffer = invocation.getArgument(2);
CompletionHandler<Integer, DataBuffer> completionHandler = invocation.getArgument(3);
completionHandler.completed(3, dataBuffer);
@@ -306,7 +306,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
String result = String.join("", Files.readAllLines(tempFile));
assertEquals("foobar", result);
assertThat(result).isEqualTo("foobar");
channel.close();
}
@@ -352,7 +352,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
String result = String.join("", Files.readAllLines(tempFile));
assertEquals("foo", result);
assertThat(result).isEqualTo("foo");
channel.close();
flux.subscribe(DataBufferUtils::release);
@@ -385,7 +385,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
String result = String.join("", Files.readAllLines(tempFile));
assertEquals("foobarbazqux", result);
assertThat(result).isEqualTo("foobarbazqux");
}
@Test
@@ -407,7 +407,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
String result = String.join("", Files.readAllLines(tempFile));
assertEquals("foobar", result);
assertThat(result).isEqualTo("foobar");
channel.close();
}
@@ -424,7 +424,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
long pos = invocation.getArgument(1);
CompletionHandler<Integer, ByteBuffer> completionHandler = invocation.getArgument(3);
assertEquals(0, pos);
assertThat(pos).isEqualTo(0);
int written = buffer.remaining();
buffer.position(buffer.limit());
@@ -468,7 +468,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
String result = String.join("", Files.readAllLines(tempFile));
assertEquals("foo", result);
assertThat(result).isEqualTo("foo");
channel.close();
flux.subscribe(DataBufferUtils::release);
@@ -495,7 +495,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
try {
String expected = String.join("", Files.readAllLines(source));
String result = String.join("", Files.readAllLines(destination));
assertEquals(expected, result);
assertThat(result).isEqualTo(expected);
}
catch (IOException e) {
throw new AssertionError(e.getMessage(), e);
@@ -530,7 +530,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
String expected = String.join("", Files.readAllLines(source));
String result = String.join("", Files.readAllLines(destination));
assertEquals(expected, result);
assertThat(result).isEqualTo(expected);
latch.countDown();
}
@@ -677,7 +677,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
private static void assertReleased(DataBuffer dataBuffer) {
if (dataBuffer instanceof NettyDataBuffer) {
ByteBuf byteBuf = ((NettyDataBuffer) dataBuffer).getNativeBuffer();
assertEquals(0, byteBuf.refCnt());
assertThat(byteBuf.refCnt()).isEqualTo(0);
}
}
@@ -720,8 +720,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
StepVerifier.create(result)
.consumeNextWith(dataBuffer -> {
assertEquals("foobarbaz",
DataBufferTestUtils.dumpString(dataBuffer, StandardCharsets.UTF_8));
assertThat(DataBufferTestUtils.dumpString(dataBuffer, StandardCharsets.UTF_8)).isEqualTo("foobarbaz");
release(dataBuffer);
})
.verifyComplete();
@@ -761,9 +760,9 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
byte[] delims = "ooba".getBytes(StandardCharsets.UTF_8);
DataBufferUtils.Matcher matcher = DataBufferUtils.matcher(delims);
int result = matcher.match(foo);
assertEquals(-1, result);
assertThat(result).isEqualTo(-1);
result = matcher.match(bar);
assertEquals(1, result);
assertThat(result).isEqualTo(1);
release(foo, bar);
@@ -776,13 +775,13 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase {
byte[] delims = "oo".getBytes(StandardCharsets.UTF_8);
DataBufferUtils.Matcher matcher = DataBufferUtils.matcher(delims);
int result = matcher.match(foo);
assertEquals(2, result);
assertThat(result).isEqualTo(2);
foo.readPosition(2);
result = matcher.match(foo);
assertEquals(3, result);
assertThat(result).isEqualTo(3);
foo.readPosition(3);
result = matcher.match(foo);
assertEquals(-1, result);
assertThat(result).isEqualTo(-1);
release(foo);
}

View File

@@ -22,9 +22,8 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Arjen Poutsma
@@ -56,9 +55,9 @@ public class PooledDataBufferTests {
buffer.retain();
boolean result = buffer.release();
assertFalse(result);
assertThat(result).isFalse();
result = buffer.release();
assertTrue(result);
assertThat(result).isTrue();
}
@Test

View File

@@ -23,8 +23,7 @@ import org.junit.Test;
import org.springframework.core.io.buffer.AbstractDataBufferAllocatingTestCase;
import org.springframework.core.io.buffer.DataBuffer;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Arjen Poutsma
@@ -39,7 +38,7 @@ public class DataBufferTestUtilsTests extends AbstractDataBufferAllocatingTestCa
byte[] result = DataBufferTestUtils.dumpBytes(buffer);
assertArrayEquals(source, result);
assertThat(result).isEqualTo(source);
release(buffer);
}
@@ -52,7 +51,7 @@ public class DataBufferTestUtilsTests extends AbstractDataBufferAllocatingTestCa
String result = DataBufferTestUtils.dumpString(buffer, StandardCharsets.UTF_8);
assertEquals(source, result);
assertThat(result).isEqualTo(source);
release(buffer);
}

View File

@@ -23,9 +23,7 @@ import org.junit.Test;
import org.springframework.core.io.DescriptiveResource;
import org.springframework.core.io.Resource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link EncodedResource}.
@@ -45,42 +43,42 @@ public class EncodedResourceTests {
@Test
public void equalsWithNullOtherObject() {
assertFalse(new EncodedResource(resource).equals(null));
assertThat(new EncodedResource(resource).equals(null)).isFalse();
}
@Test
public void equalsWithSameEncoding() {
EncodedResource er1 = new EncodedResource(resource, UTF8);
EncodedResource er2 = new EncodedResource(resource, UTF8);
assertEquals(er1, er2);
assertThat(er2).isEqualTo(er1);
}
@Test
public void equalsWithDifferentEncoding() {
EncodedResource er1 = new EncodedResource(resource, UTF8);
EncodedResource er2 = new EncodedResource(resource, UTF16);
assertNotEquals(er1, er2);
assertThat(er2).isNotEqualTo(er1);
}
@Test
public void equalsWithSameCharset() {
EncodedResource er1 = new EncodedResource(resource, UTF8_CS);
EncodedResource er2 = new EncodedResource(resource, UTF8_CS);
assertEquals(er1, er2);
assertThat(er2).isEqualTo(er1);
}
@Test
public void equalsWithDifferentCharset() {
EncodedResource er1 = new EncodedResource(resource, UTF8_CS);
EncodedResource er2 = new EncodedResource(resource, UTF16_CS);
assertNotEquals(er1, er2);
assertThat(er2).isNotEqualTo(er1);
}
@Test
public void equalsWithEncodingAndCharset() {
EncodedResource er1 = new EncodedResource(resource, UTF8);
EncodedResource er2 = new EncodedResource(resource, UTF8_CS);
assertNotEquals(er1, er2);
assertThat(er2).isNotEqualTo(er1);
}
}

View File

@@ -28,9 +28,8 @@ import org.junit.Test;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* If this test case fails, uncomment diagnostics in the
@@ -69,14 +68,14 @@ public class PathMatchingResourcePatternResolverTests {
public void singleResourceOnFileSystem() throws IOException {
Resource[] resources =
resolver.getResources("org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.class");
assertEquals(1, resources.length);
assertThat(resources.length).isEqualTo(1);
assertProtocolAndFilenames(resources, "file", "PathMatchingResourcePatternResolverTests.class");
}
@Test
public void singleResourceInJar() throws IOException {
Resource[] resources = resolver.getResources("org/reactivestreams/Publisher.class");
assertEquals(1, resources.length);
assertThat(resources.length).isEqualTo(1);
assertProtocolAndFilenames(resources, "jar", "Publisher.class");
}
@@ -119,7 +118,7 @@ public class PathMatchingResourcePatternResolverTests {
break;
}
}
assertTrue("Could not find aspectj_1_5_0.dtd in the root of the aspectjweaver jar", found);
assertThat(found).as("Could not find aspectj_1_5_0.dtd in the root of the aspectjweaver jar").isTrue();
}
@@ -144,18 +143,17 @@ public class PathMatchingResourcePatternResolverTests {
// System.out.println(resources[i]);
// }
assertEquals("Correct number of files found", filenames.length, resources.length);
assertThat(resources.length).as("Correct number of files found").isEqualTo(filenames.length);
for (Resource resource : resources) {
String actualProtocol = resource.getURL().getProtocol();
assertEquals(protocol, actualProtocol);
assertThat(actualProtocol).isEqualTo(protocol);
assertFilenameIn(resource, filenames);
}
}
private void assertFilenameIn(Resource resource, String... filenames) {
String filename = resource.getFilename();
assertTrue(resource + " does not have a filename that matches any of the specified names",
Arrays.stream(filenames).anyMatch(filename::endsWith));
assertThat(Arrays.stream(filenames).anyMatch(filename::endsWith)).as(resource + " does not have a filename that matches any of the specified names").isTrue();
}
}

View File

@@ -23,10 +23,8 @@ import org.junit.Test;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.Resource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Dave Syer
@@ -39,8 +37,8 @@ public class ResourceArrayPropertyEditorTests {
PropertyEditor editor = new ResourceArrayPropertyEditor();
editor.setAsText("classpath:org/springframework/core/io/support/ResourceArrayPropertyEditor.class");
Resource[] resources = (Resource[]) editor.getValue();
assertNotNull(resources);
assertTrue(resources[0].exists());
assertThat(resources).isNotNull();
assertThat(resources[0].exists()).isTrue();
}
@Test
@@ -52,8 +50,8 @@ public class ResourceArrayPropertyEditorTests {
PropertyEditor editor = new ResourceArrayPropertyEditor();
editor.setAsText("classpath*:org/springframework/core/io/support/Resource*Editor.class");
Resource[] resources = (Resource[]) editor.getValue();
assertNotNull(resources);
assertTrue(resources[0].exists());
assertThat(resources).isNotNull();
assertThat(resources[0].exists()).isTrue();
}
@Test
@@ -63,7 +61,7 @@ public class ResourceArrayPropertyEditorTests {
try {
editor.setAsText("${test.prop}");
Resource[] resources = (Resource[]) editor.getValue();
assertEquals("foo", resources[0].getFilename());
assertThat(resources[0].getFilename()).isEqualTo("foo");
}
finally {
System.getProperties().remove("test.prop");

View File

@@ -25,7 +25,6 @@ import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
/**
* Unit tests for {@link ResourcePropertySource}.
@@ -47,57 +46,57 @@ public class ResourcePropertySourceTests {
@Test
public void withLocationAndGeneratedName() throws IOException {
PropertySource<?> ps = new ResourcePropertySource(PROPERTIES_LOCATION);
assertEquals("bar", ps.getProperty("foo"));
assertThat(ps.getProperty("foo")).isEqualTo("bar");
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.getProperty("foo")).isEqualTo("bar");
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.getProperty("foo")).isEqualTo("bar");
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.getProperty("foo")).isEqualTo("bar");
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.getProperty("foo")).isEqualTo("bar");
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.getProperty("foo")).isEqualTo("bar");
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.getProperty("foo")).isEqualTo("bar");
assertThat(ps.getName()).isEqualTo("ps1");
}
@Test
public void withResourceHavingNoDescription() throws IOException {
PropertySource<?> ps = new ResourcePropertySource(new ByteArrayResource("foo=bar".getBytes(), ""));
assertEquals("bar", ps.getProperty("foo"));
assertEquals("Byte array resource []", ps.getName());
assertThat(ps.getProperty("foo")).isEqualTo("bar");
assertThat(ps.getName()).isEqualTo("Byte array resource []");
}
}

View File

@@ -21,10 +21,8 @@ import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Tests for {@link SpringFactoriesLoader}.
@@ -38,17 +36,19 @@ public class SpringFactoriesLoaderTests {
@Test
public void loadFactoriesInCorrectOrder() {
List<DummyFactory> factories = SpringFactoriesLoader.loadFactories(DummyFactory.class, null);
assertEquals(2, factories.size());
assertTrue(factories.get(0) instanceof MyDummyFactory1);
assertTrue(factories.get(1) instanceof MyDummyFactory2);
assertThat(factories.size()).isEqualTo(2);
boolean condition1 = factories.get(0) instanceof MyDummyFactory1;
assertThat(condition1).isTrue();
boolean condition = factories.get(1) instanceof MyDummyFactory2;
assertThat(condition).isTrue();
}
@Test
public void loadPackagePrivateFactory() {
List<DummyPackagePrivateFactory> factories =
SpringFactoriesLoader.loadFactories(DummyPackagePrivateFactory.class, null);
assertEquals(1, factories.size());
assertFalse(Modifier.isPublic(factories.get(0).getClass().getModifiers()));
assertThat(factories.size()).isEqualTo(1);
assertThat(Modifier.isPublic(factories.get(0).getClass().getModifiers())).isFalse();
}
@Test

View File

@@ -18,8 +18,7 @@ package org.springframework.core.log;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Juergen Hoeller
@@ -30,43 +29,43 @@ public class LogSupportTests {
@Test
public void testLogMessageWithSupplier() {
LogMessage msg = LogMessage.of(() -> new StringBuilder("a").append(" b"));
assertEquals("a b", msg.toString());
assertSame(msg.toString(), msg.toString());
assertThat(msg.toString()).isEqualTo("a b");
assertThat(msg.toString()).isSameAs(msg.toString());
}
@Test
public void testLogMessageWithFormat1() {
LogMessage msg = LogMessage.format("a %s", "b");
assertEquals("a b", msg.toString());
assertSame(msg.toString(), msg.toString());
assertThat(msg.toString()).isEqualTo("a b");
assertThat(msg.toString()).isSameAs(msg.toString());
}
@Test
public void testLogMessageWithFormat2() {
LogMessage msg = LogMessage.format("a %s %s", "b", "c");
assertEquals("a b c", msg.toString());
assertSame(msg.toString(), msg.toString());
assertThat(msg.toString()).isEqualTo("a b c");
assertThat(msg.toString()).isSameAs(msg.toString());
}
@Test
public void testLogMessageWithFormat3() {
LogMessage msg = LogMessage.format("a %s %s %s", "b", "c", "d");
assertEquals("a b c d", msg.toString());
assertSame(msg.toString(), msg.toString());
assertThat(msg.toString()).isEqualTo("a b c d");
assertThat(msg.toString()).isSameAs(msg.toString());
}
@Test
public void testLogMessageWithFormat4() {
LogMessage msg = LogMessage.format("a %s %s %s %s", "b", "c", "d", "e");
assertEquals("a b c d e", msg.toString());
assertSame(msg.toString(), msg.toString());
assertThat(msg.toString()).isEqualTo("a b c d e");
assertThat(msg.toString()).isSameAs(msg.toString());
}
@Test
public void testLogMessageWithFormatX() {
LogMessage msg = LogMessage.format("a %s %s %s %s %s", "b", "c", "d", "e", "f");
assertEquals("a b c d e f", msg.toString());
assertSame(msg.toString(), msg.toString());
assertThat(msg.toString()).isEqualTo("a b c d e f");
assertThat(msg.toString()).isSameAs(msg.toString());
}
}

View File

@@ -25,8 +25,8 @@ import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializationFailedException;
import org.springframework.core.serializer.support.SerializingConverter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
/**
* @author Gary Russell
@@ -40,7 +40,7 @@ public class SerializationConverterTests {
SerializingConverter toBytes = new SerializingConverter();
byte[] bytes = toBytes.convert("Testing");
DeserializingConverter fromBytes = new DeserializingConverter();
assertEquals("Testing", fromBytes.convert(bytes));
assertThat(fromBytes.convert(bytes)).isEqualTo("Testing");
}
@Test

View File

@@ -28,7 +28,7 @@ import org.junit.Test;
import org.springframework.util.ObjectUtils;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Keith Donald
@@ -69,9 +69,8 @@ public class ToStringCreatorTests {
return new ToStringCreator(this).append("familyFavoriteSport", map).toString();
}
};
assertEquals("[ToStringCreatorTests.4@" + ObjectUtils.getIdentityHexString(stringy) +
" familyFavoriteSport = map['Keri' -> 'Softball', 'Scot' -> 'Fishing', 'Keith' -> 'Flag Football']]",
stringy.toString());
assertThat(stringy.toString()).isEqualTo(("[ToStringCreatorTests.4@" + ObjectUtils.getIdentityHexString(stringy) +
" familyFavoriteSport = map['Keri' -> 'Softball', 'Scot' -> 'Fishing', 'Keith' -> 'Flag Football']]"));
}
private Map<String, String> getMap() {
@@ -86,15 +85,15 @@ public class ToStringCreatorTests {
public void defaultStyleArray() {
SomeObject[] array = new SomeObject[] {s1, s2, s3};
String str = new ToStringCreator(array).toString();
assertEquals("[@" + ObjectUtils.getIdentityHexString(array) +
" array<ToStringCreatorTests.SomeObject>[A, B, C]]", str);
assertThat(str).isEqualTo(("[@" + ObjectUtils.getIdentityHexString(array) +
" array<ToStringCreatorTests.SomeObject>[A, B, C]]"));
}
@Test
public void primitiveArrays() {
int[] integers = new int[] {0, 1, 2, 3, 4};
String str = new ToStringCreator(integers).toString();
assertEquals("[@" + ObjectUtils.getIdentityHexString(integers) + " array<Integer>[0, 1, 2, 3, 4]]", str);
assertThat(str).isEqualTo(("[@" + ObjectUtils.getIdentityHexString(integers) + " array<Integer>[0, 1, 2, 3, 4]]"));
}
@Test
@@ -104,8 +103,7 @@ public class ToStringCreatorTests {
list.add(s2);
list.add(s3);
String str = new ToStringCreator(this).append("myLetters", list).toString();
assertEquals("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) + " myLetters = list[A, B, C]]",
str);
assertThat(str).isEqualTo(("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) + " myLetters = list[A, B, C]]"));
}
@Test
@@ -115,21 +113,21 @@ public class ToStringCreatorTests {
set.add(s2);
set.add(s3);
String str = new ToStringCreator(this).append("myLetters", set).toString();
assertEquals("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) + " myLetters = set[A, B, C]]", str);
assertThat(str).isEqualTo(("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) + " myLetters = set[A, B, C]]"));
}
@Test
public void appendClass() {
String str = new ToStringCreator(this).append("myClass", this.getClass()).toString();
assertEquals("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) +
" myClass = ToStringCreatorTests]", str);
assertThat(str).isEqualTo(("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) +
" myClass = ToStringCreatorTests]"));
}
@Test
public void appendMethod() throws Exception {
String str = new ToStringCreator(this).append("myMethod", this.getClass().getMethod("appendMethod")).toString();
assertEquals("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) +
" myMethod = appendMethod@ToStringCreatorTests]", str);
assertThat(str).isEqualTo(("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) +
" myMethod = appendMethod@ToStringCreatorTests]"));
}

View File

@@ -25,9 +25,6 @@ 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.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Rick Evans
@@ -40,7 +37,7 @@ public class SimpleAsyncTaskExecutorTests {
public void cannotExecuteWhenConcurrencyIsSwitchedOff() throws Exception {
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
executor.setConcurrencyLimit(ConcurrencyThrottleSupport.NO_CONCURRENCY);
assertTrue(executor.isThrottleActive());
assertThat(executor.isThrottleActive()).isTrue();
assertThatIllegalStateException().isThrownBy(() ->
executor.execute(new NoOpRunnable()));
}
@@ -48,7 +45,7 @@ public class SimpleAsyncTaskExecutorTests {
@Test
public void throttleIsNotActiveByDefault() throws Exception {
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
assertFalse("Concurrency throttle must not default to being active (on)", executor.isThrottleActive());
assertThat(executor.isThrottleActive()).as("Concurrency throttle must not default to being active (on)").isFalse();
}
@Test
@@ -72,7 +69,7 @@ public class SimpleAsyncTaskExecutorTests {
});
ThreadNameHarvester task = new ThreadNameHarvester(monitor);
executeAndWait(executor, task, monitor);
assertEquals("test", task.getThreadName());
assertThat(task.getThreadName()).isEqualTo("test");
}
@Test

View File

@@ -39,10 +39,6 @@ import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import org.springframework.stereotype.Component;
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;
import static org.junit.Assert.assertTrue;
/**
* Unit tests demonstrating that the reflection-based {@link StandardAnnotationMetadata}
@@ -238,7 +234,7 @@ public class AnnotationMetadataTests {
@Test
public void inheritedAnnotationWithMetaAnnotationsWithIdenticalAttributeNamesUsingStandardAnnotationMetadata() {
AnnotationMetadata metadata = AnnotationMetadata.introspect(NamedComposedAnnotationExtended.class);
assertFalse(metadata.hasAnnotation(NamedComposedAnnotation.class.getName()));
assertThat(metadata.hasAnnotation(NamedComposedAnnotation.class.getName())).isFalse();
}
@Test
@@ -246,7 +242,7 @@ public class AnnotationMetadataTests {
MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(NamedComposedAnnotationExtended.class.getName());
AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
assertFalse(metadata.hasAnnotation(NamedComposedAnnotation.class.getName()));
assertThat(metadata.hasAnnotation(NamedComposedAnnotation.class.getName())).isFalse();
}
@@ -295,56 +291,56 @@ public class AnnotationMetadataTests {
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"));
assertThat(method.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value")).isEqualTo("direct");
assertThat(method.getAnnotationAttributes(DirectAnnotation.class.getName()).get("myValue")).isEqualTo("direct");
List<Object> allMeta = method.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("value");
assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet<Object>(Arrays.asList("direct", "meta")));
allMeta = method.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("additional");
assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet<Object>(Arrays.asList("direct")));
assertTrue(metadata.isAnnotated(IsAnnotatedAnnotation.class.getName()));
assertThat(metadata.isAnnotated(IsAnnotatedAnnotation.class.getName())).isTrue();
{ // perform tests with classValuesAsString = false (the default)
AnnotationAttributes specialAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(SpecialAttr.class.getName());
assertThat(specialAttrs).hasSize(6);
assertTrue(String.class.isAssignableFrom(specialAttrs.getClass("clazz")));
assertTrue(specialAttrs.getEnum("state").equals(Thread.State.NEW));
assertThat(String.class.isAssignableFrom(specialAttrs.getClass("clazz"))).isTrue();
assertThat(specialAttrs.getEnum("state").equals(Thread.State.NEW)).isTrue();
AnnotationAttributes nestedAnno = specialAttrs.getAnnotation("nestedAnno");
assertThat("na").isEqualTo(nestedAnno.getString("value"));
assertTrue(nestedAnno.getEnum("anEnum").equals(SomeEnum.LABEL1));
assertArrayEquals(new Class<?>[] {String.class}, (Class<?>[]) nestedAnno.get("classArray"));
assertThat(nestedAnno.getEnum("anEnum").equals(SomeEnum.LABEL1)).isTrue();
assertThat((Class<?>[]) nestedAnno.get("classArray")).isEqualTo(new Class<?>[] {String.class});
AnnotationAttributes[] nestedAnnoArray = specialAttrs.getAnnotationArray("nestedAnnoArray");
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[0].getEnum("anEnum").equals(SomeEnum.DEFAULT)).isTrue();
assertThat((Class<?>[]) nestedAnnoArray[0].get("classArray")).isEqualTo(new Class<?>[] {Void.class});
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"));
assertThat(nestedAnnoArray[1].getEnum("anEnum").equals(SomeEnum.LABEL2)).isTrue();
assertThat((Class<?>[]) nestedAnnoArray[1].get("classArray")).isEqualTo(new Class<?>[] {Number.class});
assertThat(nestedAnnoArray[1].getClassArray("classArray")).isEqualTo(new Class<?>[] {Number.class});
AnnotationAttributes optional = specialAttrs.getAnnotation("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"));
assertThat(optional.getEnum("anEnum").equals(SomeEnum.DEFAULT)).isTrue();
assertThat((Class<?>[]) optional.get("classArray")).isEqualTo(new Class<?>[] {Void.class});
assertThat(optional.getClassArray("classArray")).isEqualTo(new Class<?>[] {Void.class});
AnnotationAttributes[] optionalArray = specialAttrs.getAnnotationArray("optionalArray");
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"));
assertThat(optionalArray[0].getEnum("anEnum").equals(SomeEnum.DEFAULT)).isTrue();
assertThat((Class<?>[]) optionalArray[0].get("classArray")).isEqualTo(new Class<?>[] {Void.class});
assertThat(optionalArray[0].getClassArray("classArray")).isEqualTo(new Class<?>[] {Void.class});
assertEquals("direct", metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value"));
assertThat(metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value")).isEqualTo("direct");
allMeta = metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("value");
assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet<Object>(Arrays.asList("direct", "meta")));
allMeta = metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("additional");
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);
assertThat(metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("additional")).isEqualTo("");
assertThat(((String[]) metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("additionalArray")).length).isEqualTo(0);
}
{ // perform tests with classValuesAsString = true
AnnotationAttributes specialAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(
@@ -354,24 +350,24 @@ public class AnnotationMetadataTests {
assertThat(specialAttrs.getString("clazz")).isEqualTo(String.class.getName());
AnnotationAttributes nestedAnno = specialAttrs.getAnnotation("nestedAnno");
assertArrayEquals(new String[] { String.class.getName() }, nestedAnno.getStringArray("classArray"));
assertArrayEquals(new String[] { String.class.getName() }, nestedAnno.getStringArray("classArray"));
assertThat(nestedAnno.getStringArray("classArray")).isEqualTo(new String[] { String.class.getName() });
assertThat(nestedAnno.getStringArray("classArray")).isEqualTo(new String[] { String.class.getName() });
AnnotationAttributes[] nestedAnnoArray = specialAttrs.getAnnotationArray("nestedAnnoArray");
assertArrayEquals(new String[] { Void.class.getName() }, (String[]) nestedAnnoArray[0].get("classArray"));
assertArrayEquals(new String[] { Void.class.getName() }, nestedAnnoArray[0].getStringArray("classArray"));
assertArrayEquals(new String[] { Number.class.getName() }, (String[]) nestedAnnoArray[1].get("classArray"));
assertArrayEquals(new String[] { Number.class.getName() }, nestedAnnoArray[1].getStringArray("classArray"));
assertThat((String[]) nestedAnnoArray[0].get("classArray")).isEqualTo(new String[] { Void.class.getName() });
assertThat(nestedAnnoArray[0].getStringArray("classArray")).isEqualTo(new String[] { Void.class.getName() });
assertThat((String[]) nestedAnnoArray[1].get("classArray")).isEqualTo(new String[] { Number.class.getName() });
assertThat(nestedAnnoArray[1].getStringArray("classArray")).isEqualTo(new String[] { Number.class.getName() });
AnnotationAttributes optional = specialAttrs.getAnnotation("optional");
assertArrayEquals(new String[] { Void.class.getName() }, (String[]) optional.get("classArray"));
assertArrayEquals(new String[] { Void.class.getName() }, optional.getStringArray("classArray"));
assertThat((String[]) optional.get("classArray")).isEqualTo(new String[] { Void.class.getName() });
assertThat(optional.getStringArray("classArray")).isEqualTo(new String[] { Void.class.getName() });
AnnotationAttributes[] optionalArray = specialAttrs.getAnnotationArray("optionalArray");
assertArrayEquals(new String[] { Void.class.getName() }, (String[]) optionalArray[0].get("classArray"));
assertArrayEquals(new String[] { Void.class.getName() }, optionalArray[0].getStringArray("classArray"));
assertThat((String[]) optionalArray[0].get("classArray")).isEqualTo(new String[] { Void.class.getName() });
assertThat(optionalArray[0].getStringArray("classArray")).isEqualTo(new String[] { Void.class.getName() });
assertEquals("direct", metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value"));
assertThat(metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value")).isEqualTo("direct");
allMeta = metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("value");
assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet<Object>(Arrays.asList("direct", "meta")));
}

View File

@@ -28,8 +28,7 @@ import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Ramnivas Laddad
@@ -45,7 +44,7 @@ public class AnnotationTypeFilterTests {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);
AnnotationTypeFilter filter = new AnnotationTypeFilter(InheritedAnnotation.class);
assertTrue(filter.match(metadataReader, metadataReaderFactory));
assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue();
ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
@@ -57,7 +56,7 @@ public class AnnotationTypeFilterTests {
AnnotationTypeFilter filter = new AnnotationTypeFilter(InheritedAnnotation.class);
// Must fail as annotation on interfaces should not be considered a match
assertFalse(filter.match(metadataReader, metadataReaderFactory));
assertThat(filter.match(metadataReader, metadataReaderFactory)).isFalse();
ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
@@ -68,7 +67,7 @@ public class AnnotationTypeFilterTests {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);
AnnotationTypeFilter filter = new AnnotationTypeFilter(InheritedAnnotation.class);
assertTrue(filter.match(metadataReader, metadataReaderFactory));
assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue();
ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
@@ -80,7 +79,7 @@ public class AnnotationTypeFilterTests {
AnnotationTypeFilter filter = new AnnotationTypeFilter(NonInheritedAnnotation.class);
// Must fail as annotation isn't inherited
assertFalse(filter.match(metadataReader, metadataReaderFactory));
assertThat(filter.match(metadataReader, metadataReaderFactory)).isFalse();
ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
@@ -91,7 +90,7 @@ public class AnnotationTypeFilterTests {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);
AnnotationTypeFilter filter = new AnnotationTypeFilter(Component.class);
assertFalse(filter.match(metadataReader, metadataReaderFactory));
assertThat(filter.match(metadataReader, metadataReaderFactory)).isFalse();
ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
@@ -102,7 +101,7 @@ public class AnnotationTypeFilterTests {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);
AnnotationTypeFilter filter = new AnnotationTypeFilter(InheritedAnnotation.class, false, true);
assertTrue(filter.match(metadataReader, metadataReaderFactory));
assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue();
ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}

View File

@@ -24,8 +24,7 @@ import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import org.springframework.core.type.filter.AspectJTypeFilter;
import org.springframework.stereotype.Component;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Ramnivas Laddad
@@ -131,7 +130,7 @@ public class AspectJTypeFilterTests {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(type);
AspectJTypeFilter filter = new AspectJTypeFilter(typePattern, getClass().getClassLoader());
assertTrue(filter.match(metadataReader, metadataReaderFactory));
assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue();
ClassloadingAssertions.assertClassNotLoaded(type);
}
@@ -140,7 +139,7 @@ public class AspectJTypeFilterTests {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(type);
AspectJTypeFilter filter = new AspectJTypeFilter(typePattern, getClass().getClassLoader());
assertFalse(filter.match(metadataReader, metadataReaderFactory));
assertThat(filter.match(metadataReader, metadataReaderFactory)).isFalse();
ClassloadingAssertions.assertClassNotLoaded(type);
}

View File

@@ -23,8 +23,7 @@ import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import org.springframework.core.type.filter.AssignableTypeFilter;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Ramnivas Laddad
@@ -40,8 +39,8 @@ public class AssignableTypeFilterTests {
AssignableTypeFilter matchingFilter = new AssignableTypeFilter(TestNonInheritingClass.class);
AssignableTypeFilter notMatchingFilter = new AssignableTypeFilter(TestInterface.class);
assertFalse(notMatchingFilter.match(metadataReader, metadataReaderFactory));
assertTrue(matchingFilter.match(metadataReader, metadataReaderFactory));
assertThat(notMatchingFilter.match(metadataReader, metadataReaderFactory)).isFalse();
assertThat(matchingFilter.match(metadataReader, metadataReaderFactory)).isTrue();
}
@Test
@@ -51,7 +50,7 @@ public class AssignableTypeFilterTests {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);
AssignableTypeFilter filter = new AssignableTypeFilter(TestInterface.class);
assertTrue(filter.match(metadataReader, metadataReaderFactory));
assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue();
ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
@@ -62,7 +61,7 @@ public class AssignableTypeFilterTests {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);
AssignableTypeFilter filter = new AssignableTypeFilter(SimpleJdbcDaoSupport.class);
assertTrue(filter.match(metadataReader, metadataReaderFactory));
assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue();
ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
@@ -73,7 +72,7 @@ public class AssignableTypeFilterTests {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);
AssignableTypeFilter filter = new AssignableTypeFilter(JdbcDaoSupport.class);
assertTrue(filter.match(metadataReader, metadataReaderFactory));
assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue();
ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}

View File

@@ -21,7 +21,7 @@ import java.lang.reflect.Method;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import static org.junit.Assert.assertFalse;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Ramnivas Laddad
@@ -38,7 +38,7 @@ abstract class ClassloadingAssertions {
}
public static void assertClassNotLoaded(String className) {
assertFalse("Class [" + className + "] should not have been loaded", isClassLoaded(className));
assertThat(isClassLoaded(className)).as("Class [" + className + "] should not have been loaded").isFalse();
}
}

View File

@@ -25,7 +25,7 @@ import org.junit.Test;
import static java.util.stream.Collectors.joining;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.fail;
import static org.springframework.tests.Assume.TEST_GROUPS_SYSTEM_PROPERTY;
import static org.springframework.tests.TestGroup.CI;
import static org.springframework.tests.TestGroup.LONG_RUNNING;

View File

@@ -25,11 +25,8 @@ import java.util.Map;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for {@link AntPathMatcher}.
@@ -49,89 +46,90 @@ public class AntPathMatcherTests {
@Test
public void match() {
// test exact matching
assertTrue(pathMatcher.match("test", "test"));
assertTrue(pathMatcher.match("/test", "/test"));
assertTrue(pathMatcher.match("https://example.org", "https://example.org")); // SPR-14141
assertFalse(pathMatcher.match("/test.jpg", "test.jpg"));
assertFalse(pathMatcher.match("test", "/test"));
assertFalse(pathMatcher.match("/test", "test"));
assertThat(pathMatcher.match("test", "test")).isTrue();
assertThat(pathMatcher.match("/test", "/test")).isTrue();
// SPR-14141
assertThat(pathMatcher.match("https://example.org", "https://example.org")).isTrue();
assertThat(pathMatcher.match("/test.jpg", "test.jpg")).isFalse();
assertThat(pathMatcher.match("test", "/test")).isFalse();
assertThat(pathMatcher.match("/test", "test")).isFalse();
// test matching with ?'s
assertTrue(pathMatcher.match("t?st", "test"));
assertTrue(pathMatcher.match("??st", "test"));
assertTrue(pathMatcher.match("tes?", "test"));
assertTrue(pathMatcher.match("te??", "test"));
assertTrue(pathMatcher.match("?es?", "test"));
assertFalse(pathMatcher.match("tes?", "tes"));
assertFalse(pathMatcher.match("tes?", "testt"));
assertFalse(pathMatcher.match("tes?", "tsst"));
assertThat(pathMatcher.match("t?st", "test")).isTrue();
assertThat(pathMatcher.match("??st", "test")).isTrue();
assertThat(pathMatcher.match("tes?", "test")).isTrue();
assertThat(pathMatcher.match("te??", "test")).isTrue();
assertThat(pathMatcher.match("?es?", "test")).isTrue();
assertThat(pathMatcher.match("tes?", "tes")).isFalse();
assertThat(pathMatcher.match("tes?", "testt")).isFalse();
assertThat(pathMatcher.match("tes?", "tsst")).isFalse();
// test matching with *'s
assertTrue(pathMatcher.match("*", "test"));
assertTrue(pathMatcher.match("test*", "test"));
assertTrue(pathMatcher.match("test*", "testTest"));
assertTrue(pathMatcher.match("test/*", "test/Test"));
assertTrue(pathMatcher.match("test/*", "test/t"));
assertTrue(pathMatcher.match("test/*", "test/"));
assertTrue(pathMatcher.match("*test*", "AnothertestTest"));
assertTrue(pathMatcher.match("*test", "Anothertest"));
assertTrue(pathMatcher.match("*.*", "test."));
assertTrue(pathMatcher.match("*.*", "test.test"));
assertTrue(pathMatcher.match("*.*", "test.test.test"));
assertTrue(pathMatcher.match("test*aaa", "testblaaaa"));
assertFalse(pathMatcher.match("test*", "tst"));
assertFalse(pathMatcher.match("test*", "tsttest"));
assertFalse(pathMatcher.match("test*", "test/"));
assertFalse(pathMatcher.match("test*", "test/t"));
assertFalse(pathMatcher.match("test/*", "test"));
assertFalse(pathMatcher.match("*test*", "tsttst"));
assertFalse(pathMatcher.match("*test", "tsttst"));
assertFalse(pathMatcher.match("*.*", "tsttst"));
assertFalse(pathMatcher.match("test*aaa", "test"));
assertFalse(pathMatcher.match("test*aaa", "testblaaab"));
assertThat(pathMatcher.match("*", "test")).isTrue();
assertThat(pathMatcher.match("test*", "test")).isTrue();
assertThat(pathMatcher.match("test*", "testTest")).isTrue();
assertThat(pathMatcher.match("test/*", "test/Test")).isTrue();
assertThat(pathMatcher.match("test/*", "test/t")).isTrue();
assertThat(pathMatcher.match("test/*", "test/")).isTrue();
assertThat(pathMatcher.match("*test*", "AnothertestTest")).isTrue();
assertThat(pathMatcher.match("*test", "Anothertest")).isTrue();
assertThat(pathMatcher.match("*.*", "test.")).isTrue();
assertThat(pathMatcher.match("*.*", "test.test")).isTrue();
assertThat(pathMatcher.match("*.*", "test.test.test")).isTrue();
assertThat(pathMatcher.match("test*aaa", "testblaaaa")).isTrue();
assertThat(pathMatcher.match("test*", "tst")).isFalse();
assertThat(pathMatcher.match("test*", "tsttest")).isFalse();
assertThat(pathMatcher.match("test*", "test/")).isFalse();
assertThat(pathMatcher.match("test*", "test/t")).isFalse();
assertThat(pathMatcher.match("test/*", "test")).isFalse();
assertThat(pathMatcher.match("*test*", "tsttst")).isFalse();
assertThat(pathMatcher.match("*test", "tsttst")).isFalse();
assertThat(pathMatcher.match("*.*", "tsttst")).isFalse();
assertThat(pathMatcher.match("test*aaa", "test")).isFalse();
assertThat(pathMatcher.match("test*aaa", "testblaaab")).isFalse();
// test matching with ?'s and /'s
assertTrue(pathMatcher.match("/?", "/a"));
assertTrue(pathMatcher.match("/?/a", "/a/a"));
assertTrue(pathMatcher.match("/a/?", "/a/b"));
assertTrue(pathMatcher.match("/??/a", "/aa/a"));
assertTrue(pathMatcher.match("/a/??", "/a/bb"));
assertTrue(pathMatcher.match("/?", "/a"));
assertThat(pathMatcher.match("/?", "/a")).isTrue();
assertThat(pathMatcher.match("/?/a", "/a/a")).isTrue();
assertThat(pathMatcher.match("/a/?", "/a/b")).isTrue();
assertThat(pathMatcher.match("/??/a", "/aa/a")).isTrue();
assertThat(pathMatcher.match("/a/??", "/a/bb")).isTrue();
assertThat(pathMatcher.match("/?", "/a")).isTrue();
// test matching with **'s
assertTrue(pathMatcher.match("/**", "/testing/testing"));
assertTrue(pathMatcher.match("/*/**", "/testing/testing"));
assertTrue(pathMatcher.match("/**/*", "/testing/testing"));
assertTrue(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla"));
assertTrue(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla/bla"));
assertTrue(pathMatcher.match("/**/test", "/bla/bla/test"));
assertTrue(pathMatcher.match("/bla/**/**/bla", "/bla/bla/bla/bla/bla/bla"));
assertTrue(pathMatcher.match("/bla*bla/test", "/blaXXXbla/test"));
assertTrue(pathMatcher.match("/*bla/test", "/XXXbla/test"));
assertFalse(pathMatcher.match("/bla*bla/test", "/blaXXXbl/test"));
assertFalse(pathMatcher.match("/*bla/test", "XXXblab/test"));
assertFalse(pathMatcher.match("/*bla/test", "XXXbl/test"));
assertThat(pathMatcher.match("/**", "/testing/testing")).isTrue();
assertThat(pathMatcher.match("/*/**", "/testing/testing")).isTrue();
assertThat(pathMatcher.match("/**/*", "/testing/testing")).isTrue();
assertThat(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla")).isTrue();
assertThat(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla/bla")).isTrue();
assertThat(pathMatcher.match("/**/test", "/bla/bla/test")).isTrue();
assertThat(pathMatcher.match("/bla/**/**/bla", "/bla/bla/bla/bla/bla/bla")).isTrue();
assertThat(pathMatcher.match("/bla*bla/test", "/blaXXXbla/test")).isTrue();
assertThat(pathMatcher.match("/*bla/test", "/XXXbla/test")).isTrue();
assertThat(pathMatcher.match("/bla*bla/test", "/blaXXXbl/test")).isFalse();
assertThat(pathMatcher.match("/*bla/test", "XXXblab/test")).isFalse();
assertThat(pathMatcher.match("/*bla/test", "XXXbl/test")).isFalse();
assertFalse(pathMatcher.match("/????", "/bala/bla"));
assertFalse(pathMatcher.match("/**/*bla", "/bla/bla/bla/bbb"));
assertThat(pathMatcher.match("/????", "/bala/bla")).isFalse();
assertThat(pathMatcher.match("/**/*bla", "/bla/bla/bla/bbb")).isFalse();
assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/"));
assertTrue(pathMatcher.match("/*bla*/**/bla/*", "/XXXblaXXXX/testing/testing/bla/testing"));
assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing"));
assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing.jpg"));
assertThat(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/")).isTrue();
assertThat(pathMatcher.match("/*bla*/**/bla/*", "/XXXblaXXXX/testing/testing/bla/testing")).isTrue();
assertThat(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing")).isTrue();
assertThat(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing.jpg")).isTrue();
assertTrue(pathMatcher.match("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing/"));
assertTrue(pathMatcher.match("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing"));
assertTrue(pathMatcher.match("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing"));
assertFalse(pathMatcher.match("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing/testing"));
assertThat(pathMatcher.match("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing/")).isTrue();
assertThat(pathMatcher.match("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing")).isTrue();
assertThat(pathMatcher.match("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing")).isTrue();
assertThat(pathMatcher.match("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing/testing")).isFalse();
assertFalse(pathMatcher.match("/x/x/**/bla", "/x/x/x/"));
assertThat(pathMatcher.match("/x/x/**/bla", "/x/x/x/")).isFalse();
assertTrue(pathMatcher.match("/foo/bar/**", "/foo/bar")) ;
assertThat(pathMatcher.match("/foo/bar/**", "/foo/bar")).isTrue();
assertTrue(pathMatcher.match("", ""));
assertThat(pathMatcher.match("", "")).isTrue();
assertTrue(pathMatcher.match("/{bla}.*", "/testing.html"));
assertThat(pathMatcher.match("/{bla}.*", "/testing.html")).isTrue();
}
// SPR-14247
@@ -139,94 +137,94 @@ public class AntPathMatcherTests {
public void matchWithTrimTokensEnabled() throws Exception {
pathMatcher.setTrimTokens(true);
assertTrue(pathMatcher.match("/foo/bar", "/foo /bar"));
assertThat(pathMatcher.match("/foo/bar", "/foo /bar")).isTrue();
}
@Test
public void withMatchStart() {
// test exact matching
assertTrue(pathMatcher.matchStart("test", "test"));
assertTrue(pathMatcher.matchStart("/test", "/test"));
assertFalse(pathMatcher.matchStart("/test.jpg", "test.jpg"));
assertFalse(pathMatcher.matchStart("test", "/test"));
assertFalse(pathMatcher.matchStart("/test", "test"));
assertThat(pathMatcher.matchStart("test", "test")).isTrue();
assertThat(pathMatcher.matchStart("/test", "/test")).isTrue();
assertThat(pathMatcher.matchStart("/test.jpg", "test.jpg")).isFalse();
assertThat(pathMatcher.matchStart("test", "/test")).isFalse();
assertThat(pathMatcher.matchStart("/test", "test")).isFalse();
// test matching with ?'s
assertTrue(pathMatcher.matchStart("t?st", "test"));
assertTrue(pathMatcher.matchStart("??st", "test"));
assertTrue(pathMatcher.matchStart("tes?", "test"));
assertTrue(pathMatcher.matchStart("te??", "test"));
assertTrue(pathMatcher.matchStart("?es?", "test"));
assertFalse(pathMatcher.matchStart("tes?", "tes"));
assertFalse(pathMatcher.matchStart("tes?", "testt"));
assertFalse(pathMatcher.matchStart("tes?", "tsst"));
assertThat(pathMatcher.matchStart("t?st", "test")).isTrue();
assertThat(pathMatcher.matchStart("??st", "test")).isTrue();
assertThat(pathMatcher.matchStart("tes?", "test")).isTrue();
assertThat(pathMatcher.matchStart("te??", "test")).isTrue();
assertThat(pathMatcher.matchStart("?es?", "test")).isTrue();
assertThat(pathMatcher.matchStart("tes?", "tes")).isFalse();
assertThat(pathMatcher.matchStart("tes?", "testt")).isFalse();
assertThat(pathMatcher.matchStart("tes?", "tsst")).isFalse();
// test matching with *'s
assertTrue(pathMatcher.matchStart("*", "test"));
assertTrue(pathMatcher.matchStart("test*", "test"));
assertTrue(pathMatcher.matchStart("test*", "testTest"));
assertTrue(pathMatcher.matchStart("test/*", "test/Test"));
assertTrue(pathMatcher.matchStart("test/*", "test/t"));
assertTrue(pathMatcher.matchStart("test/*", "test/"));
assertTrue(pathMatcher.matchStart("*test*", "AnothertestTest"));
assertTrue(pathMatcher.matchStart("*test", "Anothertest"));
assertTrue(pathMatcher.matchStart("*.*", "test."));
assertTrue(pathMatcher.matchStart("*.*", "test.test"));
assertTrue(pathMatcher.matchStart("*.*", "test.test.test"));
assertTrue(pathMatcher.matchStart("test*aaa", "testblaaaa"));
assertFalse(pathMatcher.matchStart("test*", "tst"));
assertFalse(pathMatcher.matchStart("test*", "test/"));
assertFalse(pathMatcher.matchStart("test*", "tsttest"));
assertFalse(pathMatcher.matchStart("test*", "test/"));
assertFalse(pathMatcher.matchStart("test*", "test/t"));
assertTrue(pathMatcher.matchStart("test/*", "test"));
assertTrue(pathMatcher.matchStart("test/t*.txt", "test"));
assertFalse(pathMatcher.matchStart("*test*", "tsttst"));
assertFalse(pathMatcher.matchStart("*test", "tsttst"));
assertFalse(pathMatcher.matchStart("*.*", "tsttst"));
assertFalse(pathMatcher.matchStart("test*aaa", "test"));
assertFalse(pathMatcher.matchStart("test*aaa", "testblaaab"));
assertThat(pathMatcher.matchStart("*", "test")).isTrue();
assertThat(pathMatcher.matchStart("test*", "test")).isTrue();
assertThat(pathMatcher.matchStart("test*", "testTest")).isTrue();
assertThat(pathMatcher.matchStart("test/*", "test/Test")).isTrue();
assertThat(pathMatcher.matchStart("test/*", "test/t")).isTrue();
assertThat(pathMatcher.matchStart("test/*", "test/")).isTrue();
assertThat(pathMatcher.matchStart("*test*", "AnothertestTest")).isTrue();
assertThat(pathMatcher.matchStart("*test", "Anothertest")).isTrue();
assertThat(pathMatcher.matchStart("*.*", "test.")).isTrue();
assertThat(pathMatcher.matchStart("*.*", "test.test")).isTrue();
assertThat(pathMatcher.matchStart("*.*", "test.test.test")).isTrue();
assertThat(pathMatcher.matchStart("test*aaa", "testblaaaa")).isTrue();
assertThat(pathMatcher.matchStart("test*", "tst")).isFalse();
assertThat(pathMatcher.matchStart("test*", "test/")).isFalse();
assertThat(pathMatcher.matchStart("test*", "tsttest")).isFalse();
assertThat(pathMatcher.matchStart("test*", "test/")).isFalse();
assertThat(pathMatcher.matchStart("test*", "test/t")).isFalse();
assertThat(pathMatcher.matchStart("test/*", "test")).isTrue();
assertThat(pathMatcher.matchStart("test/t*.txt", "test")).isTrue();
assertThat(pathMatcher.matchStart("*test*", "tsttst")).isFalse();
assertThat(pathMatcher.matchStart("*test", "tsttst")).isFalse();
assertThat(pathMatcher.matchStart("*.*", "tsttst")).isFalse();
assertThat(pathMatcher.matchStart("test*aaa", "test")).isFalse();
assertThat(pathMatcher.matchStart("test*aaa", "testblaaab")).isFalse();
// test matching with ?'s and /'s
assertTrue(pathMatcher.matchStart("/?", "/a"));
assertTrue(pathMatcher.matchStart("/?/a", "/a/a"));
assertTrue(pathMatcher.matchStart("/a/?", "/a/b"));
assertTrue(pathMatcher.matchStart("/??/a", "/aa/a"));
assertTrue(pathMatcher.matchStart("/a/??", "/a/bb"));
assertTrue(pathMatcher.matchStart("/?", "/a"));
assertThat(pathMatcher.matchStart("/?", "/a")).isTrue();
assertThat(pathMatcher.matchStart("/?/a", "/a/a")).isTrue();
assertThat(pathMatcher.matchStart("/a/?", "/a/b")).isTrue();
assertThat(pathMatcher.matchStart("/??/a", "/aa/a")).isTrue();
assertThat(pathMatcher.matchStart("/a/??", "/a/bb")).isTrue();
assertThat(pathMatcher.matchStart("/?", "/a")).isTrue();
// test matching with **'s
assertTrue(pathMatcher.matchStart("/**", "/testing/testing"));
assertTrue(pathMatcher.matchStart("/*/**", "/testing/testing"));
assertTrue(pathMatcher.matchStart("/**/*", "/testing/testing"));
assertTrue(pathMatcher.matchStart("test*/**", "test/"));
assertTrue(pathMatcher.matchStart("test*/**", "test/t"));
assertTrue(pathMatcher.matchStart("/bla/**/bla", "/bla/testing/testing/bla"));
assertTrue(pathMatcher.matchStart("/bla/**/bla", "/bla/testing/testing/bla/bla"));
assertTrue(pathMatcher.matchStart("/**/test", "/bla/bla/test"));
assertTrue(pathMatcher.matchStart("/bla/**/**/bla", "/bla/bla/bla/bla/bla/bla"));
assertTrue(pathMatcher.matchStart("/bla*bla/test", "/blaXXXbla/test"));
assertTrue(pathMatcher.matchStart("/*bla/test", "/XXXbla/test"));
assertFalse(pathMatcher.matchStart("/bla*bla/test", "/blaXXXbl/test"));
assertFalse(pathMatcher.matchStart("/*bla/test", "XXXblab/test"));
assertFalse(pathMatcher.matchStart("/*bla/test", "XXXbl/test"));
assertThat(pathMatcher.matchStart("/**", "/testing/testing")).isTrue();
assertThat(pathMatcher.matchStart("/*/**", "/testing/testing")).isTrue();
assertThat(pathMatcher.matchStart("/**/*", "/testing/testing")).isTrue();
assertThat(pathMatcher.matchStart("test*/**", "test/")).isTrue();
assertThat(pathMatcher.matchStart("test*/**", "test/t")).isTrue();
assertThat(pathMatcher.matchStart("/bla/**/bla", "/bla/testing/testing/bla")).isTrue();
assertThat(pathMatcher.matchStart("/bla/**/bla", "/bla/testing/testing/bla/bla")).isTrue();
assertThat(pathMatcher.matchStart("/**/test", "/bla/bla/test")).isTrue();
assertThat(pathMatcher.matchStart("/bla/**/**/bla", "/bla/bla/bla/bla/bla/bla")).isTrue();
assertThat(pathMatcher.matchStart("/bla*bla/test", "/blaXXXbla/test")).isTrue();
assertThat(pathMatcher.matchStart("/*bla/test", "/XXXbla/test")).isTrue();
assertThat(pathMatcher.matchStart("/bla*bla/test", "/blaXXXbl/test")).isFalse();
assertThat(pathMatcher.matchStart("/*bla/test", "XXXblab/test")).isFalse();
assertThat(pathMatcher.matchStart("/*bla/test", "XXXbl/test")).isFalse();
assertFalse(pathMatcher.matchStart("/????", "/bala/bla"));
assertTrue(pathMatcher.matchStart("/**/*bla", "/bla/bla/bla/bbb"));
assertThat(pathMatcher.matchStart("/????", "/bala/bla")).isFalse();
assertThat(pathMatcher.matchStart("/**/*bla", "/bla/bla/bla/bbb")).isTrue();
assertTrue(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/"));
assertTrue(pathMatcher.matchStart("/*bla*/**/bla/*", "/XXXblaXXXX/testing/testing/bla/testing"));
assertTrue(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing"));
assertTrue(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing.jpg"));
assertThat(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/")).isTrue();
assertThat(pathMatcher.matchStart("/*bla*/**/bla/*", "/XXXblaXXXX/testing/testing/bla/testing")).isTrue();
assertThat(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing")).isTrue();
assertThat(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing.jpg")).isTrue();
assertTrue(pathMatcher.matchStart("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing/"));
assertTrue(pathMatcher.matchStart("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing"));
assertTrue(pathMatcher.matchStart("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing"));
assertTrue(pathMatcher.matchStart("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing/testing"));
assertThat(pathMatcher.matchStart("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing/")).isTrue();
assertThat(pathMatcher.matchStart("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing")).isTrue();
assertThat(pathMatcher.matchStart("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing")).isTrue();
assertThat(pathMatcher.matchStart("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing/testing")).isTrue();
assertTrue(pathMatcher.matchStart("/x/x/**/bla", "/x/x/x/"));
assertThat(pathMatcher.matchStart("/x/x/**/bla", "/x/x/x/")).isTrue();
assertTrue(pathMatcher.matchStart("", ""));
assertThat(pathMatcher.matchStart("", "")).isTrue();
}
@Test
@@ -234,123 +232,120 @@ public class AntPathMatcherTests {
pathMatcher.setPathSeparator(".");
// test exact matching
assertTrue(pathMatcher.match("test", "test"));
assertTrue(pathMatcher.match(".test", ".test"));
assertFalse(pathMatcher.match(".test/jpg", "test/jpg"));
assertFalse(pathMatcher.match("test", ".test"));
assertFalse(pathMatcher.match(".test", "test"));
assertThat(pathMatcher.match("test", "test")).isTrue();
assertThat(pathMatcher.match(".test", ".test")).isTrue();
assertThat(pathMatcher.match(".test/jpg", "test/jpg")).isFalse();
assertThat(pathMatcher.match("test", ".test")).isFalse();
assertThat(pathMatcher.match(".test", "test")).isFalse();
// test matching with ?'s
assertTrue(pathMatcher.match("t?st", "test"));
assertTrue(pathMatcher.match("??st", "test"));
assertTrue(pathMatcher.match("tes?", "test"));
assertTrue(pathMatcher.match("te??", "test"));
assertTrue(pathMatcher.match("?es?", "test"));
assertFalse(pathMatcher.match("tes?", "tes"));
assertFalse(pathMatcher.match("tes?", "testt"));
assertFalse(pathMatcher.match("tes?", "tsst"));
assertThat(pathMatcher.match("t?st", "test")).isTrue();
assertThat(pathMatcher.match("??st", "test")).isTrue();
assertThat(pathMatcher.match("tes?", "test")).isTrue();
assertThat(pathMatcher.match("te??", "test")).isTrue();
assertThat(pathMatcher.match("?es?", "test")).isTrue();
assertThat(pathMatcher.match("tes?", "tes")).isFalse();
assertThat(pathMatcher.match("tes?", "testt")).isFalse();
assertThat(pathMatcher.match("tes?", "tsst")).isFalse();
// test matching with *'s
assertTrue(pathMatcher.match("*", "test"));
assertTrue(pathMatcher.match("test*", "test"));
assertTrue(pathMatcher.match("test*", "testTest"));
assertTrue(pathMatcher.match("*test*", "AnothertestTest"));
assertTrue(pathMatcher.match("*test", "Anothertest"));
assertTrue(pathMatcher.match("*/*", "test/"));
assertTrue(pathMatcher.match("*/*", "test/test"));
assertTrue(pathMatcher.match("*/*", "test/test/test"));
assertTrue(pathMatcher.match("test*aaa", "testblaaaa"));
assertFalse(pathMatcher.match("test*", "tst"));
assertFalse(pathMatcher.match("test*", "tsttest"));
assertFalse(pathMatcher.match("*test*", "tsttst"));
assertFalse(pathMatcher.match("*test", "tsttst"));
assertFalse(pathMatcher.match("*/*", "tsttst"));
assertFalse(pathMatcher.match("test*aaa", "test"));
assertFalse(pathMatcher.match("test*aaa", "testblaaab"));
assertThat(pathMatcher.match("*", "test")).isTrue();
assertThat(pathMatcher.match("test*", "test")).isTrue();
assertThat(pathMatcher.match("test*", "testTest")).isTrue();
assertThat(pathMatcher.match("*test*", "AnothertestTest")).isTrue();
assertThat(pathMatcher.match("*test", "Anothertest")).isTrue();
assertThat(pathMatcher.match("*/*", "test/")).isTrue();
assertThat(pathMatcher.match("*/*", "test/test")).isTrue();
assertThat(pathMatcher.match("*/*", "test/test/test")).isTrue();
assertThat(pathMatcher.match("test*aaa", "testblaaaa")).isTrue();
assertThat(pathMatcher.match("test*", "tst")).isFalse();
assertThat(pathMatcher.match("test*", "tsttest")).isFalse();
assertThat(pathMatcher.match("*test*", "tsttst")).isFalse();
assertThat(pathMatcher.match("*test", "tsttst")).isFalse();
assertThat(pathMatcher.match("*/*", "tsttst")).isFalse();
assertThat(pathMatcher.match("test*aaa", "test")).isFalse();
assertThat(pathMatcher.match("test*aaa", "testblaaab")).isFalse();
// test matching with ?'s and .'s
assertTrue(pathMatcher.match(".?", ".a"));
assertTrue(pathMatcher.match(".?.a", ".a.a"));
assertTrue(pathMatcher.match(".a.?", ".a.b"));
assertTrue(pathMatcher.match(".??.a", ".aa.a"));
assertTrue(pathMatcher.match(".a.??", ".a.bb"));
assertTrue(pathMatcher.match(".?", ".a"));
assertThat(pathMatcher.match(".?", ".a")).isTrue();
assertThat(pathMatcher.match(".?.a", ".a.a")).isTrue();
assertThat(pathMatcher.match(".a.?", ".a.b")).isTrue();
assertThat(pathMatcher.match(".??.a", ".aa.a")).isTrue();
assertThat(pathMatcher.match(".a.??", ".a.bb")).isTrue();
assertThat(pathMatcher.match(".?", ".a")).isTrue();
// test matching with **'s
assertTrue(pathMatcher.match(".**", ".testing.testing"));
assertTrue(pathMatcher.match(".*.**", ".testing.testing"));
assertTrue(pathMatcher.match(".**.*", ".testing.testing"));
assertTrue(pathMatcher.match(".bla.**.bla", ".bla.testing.testing.bla"));
assertTrue(pathMatcher.match(".bla.**.bla", ".bla.testing.testing.bla.bla"));
assertTrue(pathMatcher.match(".**.test", ".bla.bla.test"));
assertTrue(pathMatcher.match(".bla.**.**.bla", ".bla.bla.bla.bla.bla.bla"));
assertTrue(pathMatcher.match(".bla*bla.test", ".blaXXXbla.test"));
assertTrue(pathMatcher.match(".*bla.test", ".XXXbla.test"));
assertFalse(pathMatcher.match(".bla*bla.test", ".blaXXXbl.test"));
assertFalse(pathMatcher.match(".*bla.test", "XXXblab.test"));
assertFalse(pathMatcher.match(".*bla.test", "XXXbl.test"));
assertThat(pathMatcher.match(".**", ".testing.testing")).isTrue();
assertThat(pathMatcher.match(".*.**", ".testing.testing")).isTrue();
assertThat(pathMatcher.match(".**.*", ".testing.testing")).isTrue();
assertThat(pathMatcher.match(".bla.**.bla", ".bla.testing.testing.bla")).isTrue();
assertThat(pathMatcher.match(".bla.**.bla", ".bla.testing.testing.bla.bla")).isTrue();
assertThat(pathMatcher.match(".**.test", ".bla.bla.test")).isTrue();
assertThat(pathMatcher.match(".bla.**.**.bla", ".bla.bla.bla.bla.bla.bla")).isTrue();
assertThat(pathMatcher.match(".bla*bla.test", ".blaXXXbla.test")).isTrue();
assertThat(pathMatcher.match(".*bla.test", ".XXXbla.test")).isTrue();
assertThat(pathMatcher.match(".bla*bla.test", ".blaXXXbl.test")).isFalse();
assertThat(pathMatcher.match(".*bla.test", "XXXblab.test")).isFalse();
assertThat(pathMatcher.match(".*bla.test", "XXXbl.test")).isFalse();
}
@Test
public void extractPathWithinPattern() throws Exception {
assertEquals("", pathMatcher.extractPathWithinPattern("/docs/commit.html", "/docs/commit.html"));
assertThat(pathMatcher.extractPathWithinPattern("/docs/commit.html", "/docs/commit.html")).isEqualTo("");
assertEquals("cvs/commit", pathMatcher.extractPathWithinPattern("/docs/*", "/docs/cvs/commit"));
assertEquals("commit.html", pathMatcher.extractPathWithinPattern("/docs/cvs/*.html", "/docs/cvs/commit.html"));
assertEquals("cvs/commit", pathMatcher.extractPathWithinPattern("/docs/**", "/docs/cvs/commit"));
assertEquals("cvs/commit.html",
pathMatcher.extractPathWithinPattern("/docs/**/*.html", "/docs/cvs/commit.html"));
assertEquals("commit.html", pathMatcher.extractPathWithinPattern("/docs/**/*.html", "/docs/commit.html"));
assertEquals("commit.html", pathMatcher.extractPathWithinPattern("/*.html", "/commit.html"));
assertEquals("docs/commit.html", pathMatcher.extractPathWithinPattern("/*.html", "/docs/commit.html"));
assertEquals("/commit.html", pathMatcher.extractPathWithinPattern("*.html", "/commit.html"));
assertEquals("/docs/commit.html", pathMatcher.extractPathWithinPattern("*.html", "/docs/commit.html"));
assertEquals("/docs/commit.html", pathMatcher.extractPathWithinPattern("**/*.*", "/docs/commit.html"));
assertEquals("/docs/commit.html", pathMatcher.extractPathWithinPattern("*", "/docs/commit.html"));
assertThat(pathMatcher.extractPathWithinPattern("/docs/*", "/docs/cvs/commit")).isEqualTo("cvs/commit");
assertThat(pathMatcher.extractPathWithinPattern("/docs/cvs/*.html", "/docs/cvs/commit.html")).isEqualTo("commit.html");
assertThat(pathMatcher.extractPathWithinPattern("/docs/**", "/docs/cvs/commit")).isEqualTo("cvs/commit");
assertThat(pathMatcher.extractPathWithinPattern("/docs/**/*.html", "/docs/cvs/commit.html")).isEqualTo("cvs/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("/docs/**/*.html", "/docs/commit.html")).isEqualTo("commit.html");
assertThat(pathMatcher.extractPathWithinPattern("/*.html", "/commit.html")).isEqualTo("commit.html");
assertThat(pathMatcher.extractPathWithinPattern("/*.html", "/docs/commit.html")).isEqualTo("docs/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("*.html", "/commit.html")).isEqualTo("/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("*.html", "/docs/commit.html")).isEqualTo("/docs/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("**/*.*", "/docs/commit.html")).isEqualTo("/docs/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("*", "/docs/commit.html")).isEqualTo("/docs/commit.html");
// SPR-10515
assertEquals("/docs/cvs/other/commit.html", pathMatcher.extractPathWithinPattern("**/commit.html", "/docs/cvs/other/commit.html"));
assertEquals("cvs/other/commit.html", pathMatcher.extractPathWithinPattern("/docs/**/commit.html", "/docs/cvs/other/commit.html"));
assertEquals("cvs/other/commit.html", pathMatcher.extractPathWithinPattern("/docs/**/**/**/**", "/docs/cvs/other/commit.html"));
assertThat(pathMatcher.extractPathWithinPattern("**/commit.html", "/docs/cvs/other/commit.html")).isEqualTo("/docs/cvs/other/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("/docs/**/commit.html", "/docs/cvs/other/commit.html")).isEqualTo("cvs/other/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("/docs/**/**/**/**", "/docs/cvs/other/commit.html")).isEqualTo("cvs/other/commit.html");
assertEquals("docs/cvs/commit", pathMatcher.extractPathWithinPattern("/d?cs/*", "/docs/cvs/commit"));
assertEquals("cvs/commit.html",
pathMatcher.extractPathWithinPattern("/docs/c?s/*.html", "/docs/cvs/commit.html"));
assertEquals("docs/cvs/commit", pathMatcher.extractPathWithinPattern("/d?cs/**", "/docs/cvs/commit"));
assertEquals("docs/cvs/commit.html",
pathMatcher.extractPathWithinPattern("/d?cs/**/*.html", "/docs/cvs/commit.html"));
assertThat(pathMatcher.extractPathWithinPattern("/d?cs/*", "/docs/cvs/commit")).isEqualTo("docs/cvs/commit");
assertThat(pathMatcher.extractPathWithinPattern("/docs/c?s/*.html", "/docs/cvs/commit.html")).isEqualTo("cvs/commit.html");
assertThat(pathMatcher.extractPathWithinPattern("/d?cs/**", "/docs/cvs/commit")).isEqualTo("docs/cvs/commit");
assertThat(pathMatcher.extractPathWithinPattern("/d?cs/**/*.html", "/docs/cvs/commit.html")).isEqualTo("docs/cvs/commit.html");
}
@Test
public void extractUriTemplateVariables() throws Exception {
Map<String, String> result = pathMatcher.extractUriTemplateVariables("/hotels/{hotel}", "/hotels/1");
assertEquals(Collections.singletonMap("hotel", "1"), result);
assertThat(result).isEqualTo(Collections.singletonMap("hotel", "1"));
result = pathMatcher.extractUriTemplateVariables("/h?tels/{hotel}", "/hotels/1");
assertEquals(Collections.singletonMap("hotel", "1"), result);
assertThat(result).isEqualTo(Collections.singletonMap("hotel", "1"));
result = pathMatcher.extractUriTemplateVariables("/hotels/{hotel}/bookings/{booking}", "/hotels/1/bookings/2");
Map<String, String> expected = new LinkedHashMap<>();
expected.put("hotel", "1");
expected.put("booking", "2");
assertEquals(expected, result);
assertThat(result).isEqualTo(expected);
result = pathMatcher.extractUriTemplateVariables("/**/hotels/**/{hotel}", "/foo/hotels/bar/1");
assertEquals(Collections.singletonMap("hotel", "1"), result);
assertThat(result).isEqualTo(Collections.singletonMap("hotel", "1"));
result = pathMatcher.extractUriTemplateVariables("/{page}.html", "/42.html");
assertEquals(Collections.singletonMap("page", "42"), result);
assertThat(result).isEqualTo(Collections.singletonMap("page", "42"));
result = pathMatcher.extractUriTemplateVariables("/{page}.*", "/42.html");
assertEquals(Collections.singletonMap("page", "42"), result);
assertThat(result).isEqualTo(Collections.singletonMap("page", "42"));
result = pathMatcher.extractUriTemplateVariables("/A-{B}-C", "/A-b-C");
assertEquals(Collections.singletonMap("B", "b"), result);
assertThat(result).isEqualTo(Collections.singletonMap("B", "b"));
result = pathMatcher.extractUriTemplateVariables("/{name}.{extension}", "/test.html");
expected = new LinkedHashMap<>();
expected.put("name", "test");
expected.put("extension", "html");
assertEquals(expected, result);
assertThat(result).isEqualTo(expected);
}
@Test
@@ -358,13 +353,13 @@ public class AntPathMatcherTests {
Map<String, String> result = pathMatcher
.extractUriTemplateVariables("{symbolicName:[\\w\\.]+}-{version:[\\w\\.]+}.jar",
"com.example-1.0.0.jar");
assertEquals("com.example", result.get("symbolicName"));
assertEquals("1.0.0", result.get("version"));
assertThat(result.get("symbolicName")).isEqualTo("com.example");
assertThat(result.get("version")).isEqualTo("1.0.0");
result = pathMatcher.extractUriTemplateVariables("{symbolicName:[\\w\\.]+}-sources-{version:[\\w\\.]+}.jar",
"com.example-sources-1.0.0.jar");
assertEquals("com.example", result.get("symbolicName"));
assertEquals("1.0.0", result.get("version"));
assertThat(result.get("symbolicName")).isEqualTo("com.example");
assertThat(result.get("version")).isEqualTo("1.0.0");
}
/**
@@ -375,23 +370,23 @@ public class AntPathMatcherTests {
Map<String, String> result = pathMatcher.extractUriTemplateVariables(
"{symbolicName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.]+}.jar",
"com.example-sources-1.0.0.jar");
assertEquals("com.example", result.get("symbolicName"));
assertEquals("1.0.0", result.get("version"));
assertThat(result.get("symbolicName")).isEqualTo("com.example");
assertThat(result.get("version")).isEqualTo("1.0.0");
result = pathMatcher.extractUriTemplateVariables(
"{symbolicName:[\\w\\.]+}-sources-{version:[\\d\\.]+}-{year:\\d{4}}{month:\\d{2}}{day:\\d{2}}.jar",
"com.example-sources-1.0.0-20100220.jar");
assertEquals("com.example", result.get("symbolicName"));
assertEquals("1.0.0", result.get("version"));
assertEquals("2010", result.get("year"));
assertEquals("02", result.get("month"));
assertEquals("20", result.get("day"));
assertThat(result.get("symbolicName")).isEqualTo("com.example");
assertThat(result.get("version")).isEqualTo("1.0.0");
assertThat(result.get("year")).isEqualTo("2010");
assertThat(result.get("month")).isEqualTo("02");
assertThat(result.get("day")).isEqualTo("20");
result = pathMatcher.extractUriTemplateVariables(
"{symbolicName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.\\{\\}]+}.jar",
"com.example-sources-1.0.0.{12}.jar");
assertEquals("com.example", result.get("symbolicName"));
assertEquals("1.0.0.{12}", result.get("version"));
assertThat(result.get("symbolicName")).isEqualTo("com.example");
assertThat(result.get("version")).isEqualTo("1.0.0.{12}");
}
/**
@@ -406,33 +401,39 @@ public class AntPathMatcherTests {
@Test
public void combine() {
assertEquals("", pathMatcher.combine(null, null));
assertEquals("/hotels", pathMatcher.combine("/hotels", null));
assertEquals("/hotels", pathMatcher.combine(null, "/hotels"));
assertEquals("/hotels/booking", pathMatcher.combine("/hotels/*", "booking"));
assertEquals("/hotels/booking", pathMatcher.combine("/hotels/*", "/booking"));
assertEquals("/hotels/**/booking", pathMatcher.combine("/hotels/**", "booking"));
assertEquals("/hotels/**/booking", pathMatcher.combine("/hotels/**", "/booking"));
assertEquals("/hotels/booking", pathMatcher.combine("/hotels", "/booking"));
assertEquals("/hotels/booking", pathMatcher.combine("/hotels", "booking"));
assertEquals("/hotels/booking", pathMatcher.combine("/hotels/", "booking"));
assertEquals("/hotels/{hotel}", pathMatcher.combine("/hotels/*", "{hotel}"));
assertEquals("/hotels/**/{hotel}", pathMatcher.combine("/hotels/**", "{hotel}"));
assertEquals("/hotels/{hotel}", pathMatcher.combine("/hotels", "{hotel}"));
assertEquals("/hotels/{hotel}.*", pathMatcher.combine("/hotels", "{hotel}.*"));
assertEquals("/hotels/*/booking/{booking}", pathMatcher.combine("/hotels/*/booking", "{booking}"));
assertEquals("/hotel.html", pathMatcher.combine("/*.html", "/hotel.html"));
assertEquals("/hotel.html", pathMatcher.combine("/*.html", "/hotel"));
assertEquals("/hotel.html", pathMatcher.combine("/*.html", "/hotel.*"));
assertEquals("/*.html", pathMatcher.combine("/**", "/*.html"));
assertEquals("/*.html", pathMatcher.combine("/*", "/*.html"));
assertEquals("/*.html", pathMatcher.combine("/*.*", "/*.html"));
assertEquals("/{foo}/bar", pathMatcher.combine("/{foo}", "/bar")); // SPR-8858
assertEquals("/user/user", pathMatcher.combine("/user", "/user")); // SPR-7970
assertEquals("/{foo:.*[^0-9].*}/edit/", pathMatcher.combine("/{foo:.*[^0-9].*}", "/edit/")); // SPR-10062
assertEquals("/1.0/foo/test", pathMatcher.combine("/1.0", "/foo/test")); // SPR-10554
assertEquals("/hotel", pathMatcher.combine("/", "/hotel")); // SPR-12975
assertEquals("/hotel/booking", pathMatcher.combine("/hotel/", "/booking")); // SPR-12975
assertThat(pathMatcher.combine(null, null)).isEqualTo("");
assertThat(pathMatcher.combine("/hotels", null)).isEqualTo("/hotels");
assertThat(pathMatcher.combine(null, "/hotels")).isEqualTo("/hotels");
assertThat(pathMatcher.combine("/hotels/*", "booking")).isEqualTo("/hotels/booking");
assertThat(pathMatcher.combine("/hotels/*", "/booking")).isEqualTo("/hotels/booking");
assertThat(pathMatcher.combine("/hotels/**", "booking")).isEqualTo("/hotels/**/booking");
assertThat(pathMatcher.combine("/hotels/**", "/booking")).isEqualTo("/hotels/**/booking");
assertThat(pathMatcher.combine("/hotels", "/booking")).isEqualTo("/hotels/booking");
assertThat(pathMatcher.combine("/hotels", "booking")).isEqualTo("/hotels/booking");
assertThat(pathMatcher.combine("/hotels/", "booking")).isEqualTo("/hotels/booking");
assertThat(pathMatcher.combine("/hotels/*", "{hotel}")).isEqualTo("/hotels/{hotel}");
assertThat(pathMatcher.combine("/hotels/**", "{hotel}")).isEqualTo("/hotels/**/{hotel}");
assertThat(pathMatcher.combine("/hotels", "{hotel}")).isEqualTo("/hotels/{hotel}");
assertThat(pathMatcher.combine("/hotels", "{hotel}.*")).isEqualTo("/hotels/{hotel}.*");
assertThat(pathMatcher.combine("/hotels/*/booking", "{booking}")).isEqualTo("/hotels/*/booking/{booking}");
assertThat(pathMatcher.combine("/*.html", "/hotel.html")).isEqualTo("/hotel.html");
assertThat(pathMatcher.combine("/*.html", "/hotel")).isEqualTo("/hotel.html");
assertThat(pathMatcher.combine("/*.html", "/hotel.*")).isEqualTo("/hotel.html");
assertThat(pathMatcher.combine("/**", "/*.html")).isEqualTo("/*.html");
assertThat(pathMatcher.combine("/*", "/*.html")).isEqualTo("/*.html");
assertThat(pathMatcher.combine("/*.*", "/*.html")).isEqualTo("/*.html");
// SPR-8858
assertThat(pathMatcher.combine("/{foo}", "/bar")).isEqualTo("/{foo}/bar");
// SPR-7970
assertThat(pathMatcher.combine("/user", "/user")).isEqualTo("/user/user");
// SPR-10062
assertThat(pathMatcher.combine("/{foo:.*[^0-9].*}", "/edit/")).isEqualTo("/{foo:.*[^0-9].*}/edit/");
// SPR-10554
assertThat(pathMatcher.combine("/1.0", "/foo/test")).isEqualTo("/1.0/foo/test");
// SPR-12975
assertThat(pathMatcher.combine("/", "/hotel")).isEqualTo("/hotel");
// SPR-12975
assertThat(pathMatcher.combine("/hotel/", "/booking")).isEqualTo("/hotel/booking");
}
@Test
@@ -445,53 +446,53 @@ public class AntPathMatcherTests {
public void patternComparator() {
Comparator<String> comparator = pathMatcher.getPatternComparator("/hotels/new");
assertEquals(0, comparator.compare(null, null));
assertEquals(1, comparator.compare(null, "/hotels/new"));
assertEquals(-1, comparator.compare("/hotels/new", null));
assertThat(comparator.compare(null, null)).isEqualTo(0);
assertThat(comparator.compare(null, "/hotels/new")).isEqualTo(1);
assertThat(comparator.compare("/hotels/new", null)).isEqualTo(-1);
assertEquals(0, comparator.compare("/hotels/new", "/hotels/new"));
assertThat(comparator.compare("/hotels/new", "/hotels/new")).isEqualTo(0);
assertEquals(-1, comparator.compare("/hotels/new", "/hotels/*"));
assertEquals(1, comparator.compare("/hotels/*", "/hotels/new"));
assertEquals(0, comparator.compare("/hotels/*", "/hotels/*"));
assertThat(comparator.compare("/hotels/new", "/hotels/*")).isEqualTo(-1);
assertThat(comparator.compare("/hotels/*", "/hotels/new")).isEqualTo(1);
assertThat(comparator.compare("/hotels/*", "/hotels/*")).isEqualTo(0);
assertEquals(-1, comparator.compare("/hotels/new", "/hotels/{hotel}"));
assertEquals(1, comparator.compare("/hotels/{hotel}", "/hotels/new"));
assertEquals(0, comparator.compare("/hotels/{hotel}", "/hotels/{hotel}"));
assertEquals(-1, comparator.compare("/hotels/{hotel}/booking", "/hotels/{hotel}/bookings/{booking}"));
assertEquals(1, comparator.compare("/hotels/{hotel}/bookings/{booking}", "/hotels/{hotel}/booking"));
assertThat(comparator.compare("/hotels/new", "/hotels/{hotel}")).isEqualTo(-1);
assertThat(comparator.compare("/hotels/{hotel}", "/hotels/new")).isEqualTo(1);
assertThat(comparator.compare("/hotels/{hotel}", "/hotels/{hotel}")).isEqualTo(0);
assertThat(comparator.compare("/hotels/{hotel}/booking", "/hotels/{hotel}/bookings/{booking}")).isEqualTo(-1);
assertThat(comparator.compare("/hotels/{hotel}/bookings/{booking}", "/hotels/{hotel}/booking")).isEqualTo(1);
// SPR-10550
assertEquals(-1, comparator.compare("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}", "/**"));
assertEquals(1, comparator.compare("/**", "/hotels/{hotel}/bookings/{booking}/cutomers/{customer}"));
assertEquals(0, comparator.compare("/**", "/**"));
assertThat(comparator.compare("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}", "/**")).isEqualTo(-1);
assertThat(comparator.compare("/**", "/hotels/{hotel}/bookings/{booking}/cutomers/{customer}")).isEqualTo(1);
assertThat(comparator.compare("/**", "/**")).isEqualTo(0);
assertEquals(-1, comparator.compare("/hotels/{hotel}", "/hotels/*"));
assertEquals(1, comparator.compare("/hotels/*", "/hotels/{hotel}"));
assertThat(comparator.compare("/hotels/{hotel}", "/hotels/*")).isEqualTo(-1);
assertThat(comparator.compare("/hotels/*", "/hotels/{hotel}")).isEqualTo(1);
assertEquals(-1, comparator.compare("/hotels/*", "/hotels/*/**"));
assertEquals(1, comparator.compare("/hotels/*/**", "/hotels/*"));
assertThat(comparator.compare("/hotels/*", "/hotels/*/**")).isEqualTo(-1);
assertThat(comparator.compare("/hotels/*/**", "/hotels/*")).isEqualTo(1);
assertEquals(-1, comparator.compare("/hotels/new", "/hotels/new.*"));
assertEquals(2, comparator.compare("/hotels/{hotel}", "/hotels/{hotel}.*"));
assertThat(comparator.compare("/hotels/new", "/hotels/new.*")).isEqualTo(-1);
assertThat(comparator.compare("/hotels/{hotel}", "/hotels/{hotel}.*")).isEqualTo(2);
// SPR-6741
assertEquals(-1, comparator.compare("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}", "/hotels/**"));
assertEquals(1, comparator.compare("/hotels/**", "/hotels/{hotel}/bookings/{booking}/cutomers/{customer}"));
assertEquals(1, comparator.compare("/hotels/foo/bar/**", "/hotels/{hotel}"));
assertEquals(-1, comparator.compare("/hotels/{hotel}", "/hotels/foo/bar/**"));
assertEquals(2, comparator.compare("/hotels/**/bookings/**", "/hotels/**"));
assertEquals(-2, comparator.compare("/hotels/**", "/hotels/**/bookings/**"));
assertThat(comparator.compare("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}", "/hotels/**")).isEqualTo(-1);
assertThat(comparator.compare("/hotels/**", "/hotels/{hotel}/bookings/{booking}/cutomers/{customer}")).isEqualTo(1);
assertThat(comparator.compare("/hotels/foo/bar/**", "/hotels/{hotel}")).isEqualTo(1);
assertThat(comparator.compare("/hotels/{hotel}", "/hotels/foo/bar/**")).isEqualTo(-1);
assertThat(comparator.compare("/hotels/**/bookings/**", "/hotels/**")).isEqualTo(2);
assertThat(comparator.compare("/hotels/**", "/hotels/**/bookings/**")).isEqualTo(-2);
// SPR-8683
assertEquals(1, comparator.compare("/**", "/hotels/{hotel}"));
assertThat(comparator.compare("/**", "/hotels/{hotel}")).isEqualTo(1);
// longer is better
assertEquals(1, comparator.compare("/hotels", "/hotels2"));
assertThat(comparator.compare("/hotels", "/hotels2")).isEqualTo(1);
// SPR-13139
assertEquals(-1, comparator.compare("*", "*/**"));
assertEquals(1, comparator.compare("*/**", "*"));
assertThat(comparator.compare("*", "*/**")).isEqualTo(-1);
assertThat(comparator.compare("*/**", "*")).isEqualTo(1);
}
@Test
@@ -502,74 +503,74 @@ public class AntPathMatcherTests {
paths.add(null);
paths.add("/hotels/new");
Collections.sort(paths, comparator);
assertEquals("/hotels/new", paths.get(0));
assertNull(paths.get(1));
assertThat(paths.get(0)).isEqualTo("/hotels/new");
assertThat(paths.get(1)).isNull();
paths.clear();
paths.add("/hotels/new");
paths.add(null);
Collections.sort(paths, comparator);
assertEquals("/hotels/new", paths.get(0));
assertNull(paths.get(1));
assertThat(paths.get(0)).isEqualTo("/hotels/new");
assertThat(paths.get(1)).isNull();
paths.clear();
paths.add("/hotels/*");
paths.add("/hotels/new");
Collections.sort(paths, comparator);
assertEquals("/hotels/new", paths.get(0));
assertEquals("/hotels/*", paths.get(1));
assertThat(paths.get(0)).isEqualTo("/hotels/new");
assertThat(paths.get(1)).isEqualTo("/hotels/*");
paths.clear();
paths.add("/hotels/new");
paths.add("/hotels/*");
Collections.sort(paths, comparator);
assertEquals("/hotels/new", paths.get(0));
assertEquals("/hotels/*", paths.get(1));
assertThat(paths.get(0)).isEqualTo("/hotels/new");
assertThat(paths.get(1)).isEqualTo("/hotels/*");
paths.clear();
paths.add("/hotels/**");
paths.add("/hotels/*");
Collections.sort(paths, comparator);
assertEquals("/hotels/*", paths.get(0));
assertEquals("/hotels/**", paths.get(1));
assertThat(paths.get(0)).isEqualTo("/hotels/*");
assertThat(paths.get(1)).isEqualTo("/hotels/**");
paths.clear();
paths.add("/hotels/*");
paths.add("/hotels/**");
Collections.sort(paths, comparator);
assertEquals("/hotels/*", paths.get(0));
assertEquals("/hotels/**", paths.get(1));
assertThat(paths.get(0)).isEqualTo("/hotels/*");
assertThat(paths.get(1)).isEqualTo("/hotels/**");
paths.clear();
paths.add("/hotels/{hotel}");
paths.add("/hotels/new");
Collections.sort(paths, comparator);
assertEquals("/hotels/new", paths.get(0));
assertEquals("/hotels/{hotel}", paths.get(1));
assertThat(paths.get(0)).isEqualTo("/hotels/new");
assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}");
paths.clear();
paths.add("/hotels/new");
paths.add("/hotels/{hotel}");
Collections.sort(paths, comparator);
assertEquals("/hotels/new", paths.get(0));
assertEquals("/hotels/{hotel}", paths.get(1));
assertThat(paths.get(0)).isEqualTo("/hotels/new");
assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}");
paths.clear();
paths.add("/hotels/*");
paths.add("/hotels/{hotel}");
paths.add("/hotels/new");
Collections.sort(paths, comparator);
assertEquals("/hotels/new", paths.get(0));
assertEquals("/hotels/{hotel}", paths.get(1));
assertEquals("/hotels/*", paths.get(2));
assertThat(paths.get(0)).isEqualTo("/hotels/new");
assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}");
assertThat(paths.get(2)).isEqualTo("/hotels/*");
paths.clear();
paths.add("/hotels/ne*");
paths.add("/hotels/n*");
Collections.shuffle(paths);
Collections.sort(paths, comparator);
assertEquals("/hotels/ne*", paths.get(0));
assertEquals("/hotels/n*", paths.get(1));
assertThat(paths.get(0)).isEqualTo("/hotels/ne*");
assertThat(paths.get(1)).isEqualTo("/hotels/n*");
paths.clear();
comparator = pathMatcher.getPatternComparator("/hotels/new.html");
@@ -577,16 +578,16 @@ public class AntPathMatcherTests {
paths.add("/hotels/{hotel}");
Collections.shuffle(paths);
Collections.sort(paths, comparator);
assertEquals("/hotels/new.*", paths.get(0));
assertEquals("/hotels/{hotel}", paths.get(1));
assertThat(paths.get(0)).isEqualTo("/hotels/new.*");
assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}");
paths.clear();
comparator = pathMatcher.getPatternComparator("/web/endUser/action/login.html");
paths.add("/**/login.*");
paths.add("/**/endUser/action/login.*");
Collections.sort(paths, comparator);
assertEquals("/**/endUser/action/login.*", paths.get(0));
assertEquals("/**/login.*", paths.get(1));
assertThat(paths.get(0)).isEqualTo("/**/endUser/action/login.*");
assertThat(paths.get(1)).isEqualTo("/**/login.*");
paths.clear();
}
@@ -594,64 +595,64 @@ public class AntPathMatcherTests {
public void trimTokensOff() {
pathMatcher.setTrimTokens(false);
assertTrue(pathMatcher.match("/group/{groupName}/members", "/group/sales/members"));
assertTrue(pathMatcher.match("/group/{groupName}/members", "/group/ sales/members"));
assertFalse(pathMatcher.match("/group/{groupName}/members", "/Group/ Sales/Members"));
assertThat(pathMatcher.match("/group/{groupName}/members", "/group/sales/members")).isTrue();
assertThat(pathMatcher.match("/group/{groupName}/members", "/group/ sales/members")).isTrue();
assertThat(pathMatcher.match("/group/{groupName}/members", "/Group/ Sales/Members")).isFalse();
}
@Test // SPR-13286
public void caseInsensitive() {
pathMatcher.setCaseSensitive(false);
assertTrue(pathMatcher.match("/group/{groupName}/members", "/group/sales/members"));
assertTrue(pathMatcher.match("/group/{groupName}/members", "/Group/Sales/Members"));
assertTrue(pathMatcher.match("/Group/{groupName}/Members", "/group/Sales/members"));
assertThat(pathMatcher.match("/group/{groupName}/members", "/group/sales/members")).isTrue();
assertThat(pathMatcher.match("/group/{groupName}/members", "/Group/Sales/Members")).isTrue();
assertThat(pathMatcher.match("/Group/{groupName}/Members", "/group/Sales/members")).isTrue();
}
@Test
public void defaultCacheSetting() {
match();
assertTrue(pathMatcher.stringMatcherCache.size() > 20);
assertThat(pathMatcher.stringMatcherCache.size() > 20).isTrue();
for (int i = 0; i < 65536; i++) {
pathMatcher.match("test" + i, "test");
}
// Cache turned off because it went beyond the threshold
assertTrue(pathMatcher.stringMatcherCache.isEmpty());
assertThat(pathMatcher.stringMatcherCache.isEmpty()).isTrue();
}
@Test
public void cachePatternsSetToTrue() {
pathMatcher.setCachePatterns(true);
match();
assertTrue(pathMatcher.stringMatcherCache.size() > 20);
assertThat(pathMatcher.stringMatcherCache.size() > 20).isTrue();
for (int i = 0; i < 65536; i++) {
pathMatcher.match("test" + i, "test" + i);
}
// Cache keeps being alive due to the explicit cache setting
assertTrue(pathMatcher.stringMatcherCache.size() > 65536);
assertThat(pathMatcher.stringMatcherCache.size() > 65536).isTrue();
}
@Test
public void preventCreatingStringMatchersIfPathDoesNotStartsWithPatternPrefix() {
pathMatcher.setCachePatterns(true);
assertEquals(0, pathMatcher.stringMatcherCache.size());
assertThat(pathMatcher.stringMatcherCache.size()).isEqualTo(0);
pathMatcher.match("test?", "test");
assertEquals(1, pathMatcher.stringMatcherCache.size());
assertThat(pathMatcher.stringMatcherCache.size()).isEqualTo(1);
pathMatcher.match("test?", "best");
pathMatcher.match("test/*", "view/test.jpg");
pathMatcher.match("test/**/test.jpg", "view/test.jpg");
pathMatcher.match("test/{name}.jpg", "view/test.jpg");
assertEquals(1, pathMatcher.stringMatcherCache.size());
assertThat(pathMatcher.stringMatcherCache.size()).isEqualTo(1);
}
@Test
public void creatingStringMatchersIfPatternPrefixCannotDetermineIfPathMatch() {
pathMatcher.setCachePatterns(true);
assertEquals(0, pathMatcher.stringMatcherCache.size());
assertThat(pathMatcher.stringMatcherCache.size()).isEqualTo(0);
pathMatcher.match("test", "testian");
pathMatcher.match("test?", "testFf");
@@ -662,31 +663,30 @@ public class AntPathMatcherTests {
pathMatcher.match("/**/{name}.jpg", "/test/lorem.jpg");
pathMatcher.match("/*/dir/{name}.jpg", "/*/dir/lorem.jpg");
assertEquals(7, pathMatcher.stringMatcherCache.size());
assertThat(pathMatcher.stringMatcherCache.size()).isEqualTo(7);
}
@Test
public void cachePatternsSetToFalse() {
pathMatcher.setCachePatterns(false);
match();
assertTrue(pathMatcher.stringMatcherCache.isEmpty());
assertThat(pathMatcher.stringMatcherCache.isEmpty()).isTrue();
}
@Test
public void extensionMappingWithDotPathSeparator() {
pathMatcher.setPathSeparator(".");
assertEquals("Extension mapping should be disabled with \".\" as path separator",
"/*.html.hotel.*", pathMatcher.combine("/*.html", "hotel.*"));
assertThat(pathMatcher.combine("/*.html", "hotel.*")).as("Extension mapping should be disabled with \".\" as path separator").isEqualTo("/*.html.hotel.*");
}
@Test // gh-22959
public void isPattern() {
assertTrue(pathMatcher.isPattern("/test/*"));
assertTrue(pathMatcher.isPattern("/test/**/name"));
assertTrue(pathMatcher.isPattern("/test?"));
assertTrue(pathMatcher.isPattern("/test/{name}"));
assertFalse(pathMatcher.isPattern("/test/name"));
assertFalse(pathMatcher.isPattern("/test/foo{bar"));
assertThat(pathMatcher.isPattern("/test/*")).isTrue();
assertThat(pathMatcher.isPattern("/test/**/name")).isTrue();
assertThat(pathMatcher.isPattern("/test?")).isTrue();
assertThat(pathMatcher.isPattern("/test/{name}")).isTrue();
assertThat(pathMatcher.isPattern("/test/name")).isFalse();
assertThat(pathMatcher.isPattern("/test/foo{bar")).isFalse();
}
}

View File

@@ -22,10 +22,7 @@ import org.junit.Test;
import org.springframework.tests.sample.objects.TestObject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Harrop
@@ -57,21 +54,26 @@ public class AutoPopulatingListTests {
Object lastElement = null;
for (int x = 0; x < 10; x++) {
Object element = list.get(x);
assertNotNull("Element is null", list.get(x));
assertTrue("Element is incorrect type", element instanceof TestObject);
assertNotSame(lastElement, element);
assertThat(list.get(x)).as("Element is null").isNotNull();
boolean condition = element instanceof TestObject;
assertThat(condition).as("Element is incorrect type").isTrue();
assertThat(element).isNotSameAs(lastElement);
lastElement = element;
}
String helloWorld = "Hello World!";
list.add(10, null);
list.add(11, helloWorld);
assertEquals(helloWorld, list.get(11));
assertThat(list.get(11)).isEqualTo(helloWorld);
assertTrue(list.get(10) instanceof TestObject);
assertTrue(list.get(12) instanceof TestObject);
assertTrue(list.get(13) instanceof TestObject);
assertTrue(list.get(20) instanceof TestObject);
boolean condition3 = list.get(10) instanceof TestObject;
assertThat(condition3).isTrue();
boolean condition2 = list.get(12) instanceof TestObject;
assertThat(condition2).isTrue();
boolean condition1 = list.get(13) instanceof TestObject;
assertThat(condition1).isTrue();
boolean condition = list.get(20) instanceof TestObject;
assertThat(condition).isTrue();
}
private void doTestWithElementFactory(AutoPopulatingList<Object> list) {
@@ -80,7 +82,7 @@ public class AutoPopulatingListTests {
for (int x = 0; x < list.size(); x++) {
Object element = list.get(x);
if (element instanceof TestObject) {
assertEquals(x, ((TestObject) element).getAge());
assertThat(((TestObject) element).getAge()).isEqualTo(x);
}
}
}
@@ -88,7 +90,7 @@ public class AutoPopulatingListTests {
@Test
public void serialization() throws Exception {
AutoPopulatingList<?> list = new AutoPopulatingList<Object>(TestObject.class);
assertEquals(list, SerializationTestUtils.serializeAndDeserialize(list));
assertThat(SerializationTestUtils.serializeAndDeserialize(list)).isEqualTo(list);
}

View File

@@ -21,8 +21,7 @@ import javax.xml.bind.DatatypeConverter;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Juergen Hoeller
@@ -34,57 +33,57 @@ public class Base64UtilsTests {
public void encode() throws UnsupportedEncodingException {
byte[] bytes = new byte[]
{-0x4f, 0xa, -0x73, -0x4f, 0x64, -0x20, 0x75, 0x41, 0x5, -0x49, -0x57, -0x65, -0x19, 0x2e, 0x3f, -0x1b};
assertArrayEquals(bytes, Base64Utils.decode(Base64Utils.encode(bytes)));
assertThat(Base64Utils.decode(Base64Utils.encode(bytes))).isEqualTo(bytes);
bytes = "Hello World".getBytes("UTF-8");
assertArrayEquals(bytes, Base64Utils.decode(Base64Utils.encode(bytes)));
assertThat(Base64Utils.decode(Base64Utils.encode(bytes))).isEqualTo(bytes);
bytes = "Hello World\r\nSecond Line".getBytes("UTF-8");
assertArrayEquals(bytes, Base64Utils.decode(Base64Utils.encode(bytes)));
assertThat(Base64Utils.decode(Base64Utils.encode(bytes))).isEqualTo(bytes);
bytes = "Hello World\r\nSecond Line\r\n".getBytes("UTF-8");
assertArrayEquals(bytes, Base64Utils.decode(Base64Utils.encode(bytes)));
assertThat(Base64Utils.decode(Base64Utils.encode(bytes))).isEqualTo(bytes);
bytes = new byte[] { (byte) 0xfb, (byte) 0xf0 };
assertArrayEquals("+/A=".getBytes(), Base64Utils.encode(bytes));
assertArrayEquals(bytes, Base64Utils.decode(Base64Utils.encode(bytes)));
assertThat(Base64Utils.encode(bytes)).isEqualTo("+/A=".getBytes());
assertThat(Base64Utils.decode(Base64Utils.encode(bytes))).isEqualTo(bytes);
assertArrayEquals("-_A=".getBytes(), Base64Utils.encodeUrlSafe(bytes));
assertArrayEquals(bytes, Base64Utils.decodeUrlSafe(Base64Utils.encodeUrlSafe(bytes)));
assertThat(Base64Utils.encodeUrlSafe(bytes)).isEqualTo("-_A=".getBytes());
assertThat(Base64Utils.decodeUrlSafe(Base64Utils.encodeUrlSafe(bytes))).isEqualTo(bytes);
}
@Test
public void encodeToStringWithJdk8VsJaxb() throws UnsupportedEncodingException {
byte[] bytes = new byte[]
{-0x4f, 0xa, -0x73, -0x4f, 0x64, -0x20, 0x75, 0x41, 0x5, -0x49, -0x57, -0x65, -0x19, 0x2e, 0x3f, -0x1b};
assertEquals(Base64Utils.encodeToString(bytes), DatatypeConverter.printBase64Binary(bytes));
assertArrayEquals(bytes, Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes)));
assertArrayEquals(bytes, DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes)));
assertThat(DatatypeConverter.printBase64Binary(bytes)).isEqualTo(Base64Utils.encodeToString(bytes));
assertThat(Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes))).isEqualTo(bytes);
assertThat(DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes))).isEqualTo(bytes);
bytes = "Hello World".getBytes("UTF-8");
assertEquals(Base64Utils.encodeToString(bytes), DatatypeConverter.printBase64Binary(bytes));
assertArrayEquals(bytes, Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes)));
assertArrayEquals(bytes, DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes)));
assertThat(DatatypeConverter.printBase64Binary(bytes)).isEqualTo(Base64Utils.encodeToString(bytes));
assertThat(Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes))).isEqualTo(bytes);
assertThat(DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes))).isEqualTo(bytes);
bytes = "Hello World\r\nSecond Line".getBytes("UTF-8");
assertEquals(Base64Utils.encodeToString(bytes), DatatypeConverter.printBase64Binary(bytes));
assertArrayEquals(bytes, Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes)));
assertArrayEquals(bytes, DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes)));
assertThat(DatatypeConverter.printBase64Binary(bytes)).isEqualTo(Base64Utils.encodeToString(bytes));
assertThat(Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes))).isEqualTo(bytes);
assertThat(DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes))).isEqualTo(bytes);
bytes = "Hello World\r\nSecond Line\r\n".getBytes("UTF-8");
assertEquals(Base64Utils.encodeToString(bytes), DatatypeConverter.printBase64Binary(bytes));
assertArrayEquals(bytes, Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes)));
assertArrayEquals(bytes, DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes)));
assertThat(DatatypeConverter.printBase64Binary(bytes)).isEqualTo(Base64Utils.encodeToString(bytes));
assertThat(Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes))).isEqualTo(bytes);
assertThat(DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes))).isEqualTo(bytes);
}
@Test
public void encodeDecodeUrlSafe() {
byte[] bytes = new byte[] { (byte) 0xfb, (byte) 0xf0 };
assertArrayEquals("-_A=".getBytes(), Base64Utils.encodeUrlSafe(bytes));
assertArrayEquals(bytes, Base64Utils.decodeUrlSafe(Base64Utils.encodeUrlSafe(bytes)));
assertThat(Base64Utils.encodeUrlSafe(bytes)).isEqualTo("-_A=".getBytes());
assertThat(Base64Utils.decodeUrlSafe(Base64Utils.encodeUrlSafe(bytes))).isEqualTo(bytes);
assertEquals("-_A=", Base64Utils.encodeToUrlSafeString(bytes));
assertArrayEquals(bytes, Base64Utils.decodeFromUrlSafeString(Base64Utils.encodeToUrlSafeString(bytes)));
assertThat(Base64Utils.encodeToUrlSafeString(bytes)).isEqualTo("-_A=");
assertThat(Base64Utils.decodeFromUrlSafeString(Base64Utils.encodeToUrlSafeString(bytes))).isEqualTo(bytes);
}
}

View File

@@ -37,11 +37,7 @@ import org.springframework.tests.sample.objects.ITestInterface;
import org.springframework.tests.sample.objects.ITestObject;
import org.springframework.tests.sample.objects.TestObject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Colin Sampaleanu
@@ -64,60 +60,60 @@ public class ClassUtilsTests {
@Test
public void testIsPresent() {
assertTrue(ClassUtils.isPresent("java.lang.String", classLoader));
assertFalse(ClassUtils.isPresent("java.lang.MySpecialString", classLoader));
assertThat(ClassUtils.isPresent("java.lang.String", classLoader)).isTrue();
assertThat(ClassUtils.isPresent("java.lang.MySpecialString", classLoader)).isFalse();
}
@Test
public void testForName() throws ClassNotFoundException {
assertEquals(String.class, ClassUtils.forName("java.lang.String", classLoader));
assertEquals(String[].class, ClassUtils.forName("java.lang.String[]", classLoader));
assertEquals(String[].class, ClassUtils.forName(String[].class.getName(), classLoader));
assertEquals(String[][].class, ClassUtils.forName(String[][].class.getName(), classLoader));
assertEquals(String[][][].class, ClassUtils.forName(String[][][].class.getName(), classLoader));
assertEquals(TestObject.class, ClassUtils.forName("org.springframework.tests.sample.objects.TestObject", classLoader));
assertEquals(TestObject[].class, ClassUtils.forName("org.springframework.tests.sample.objects.TestObject[]", classLoader));
assertEquals(TestObject[].class, ClassUtils.forName(TestObject[].class.getName(), classLoader));
assertEquals(TestObject[][].class, ClassUtils.forName("org.springframework.tests.sample.objects.TestObject[][]", classLoader));
assertEquals(TestObject[][].class, ClassUtils.forName(TestObject[][].class.getName(), classLoader));
assertEquals(short[][][].class, ClassUtils.forName("[[[S", classLoader));
assertThat(ClassUtils.forName("java.lang.String", classLoader)).isEqualTo(String.class);
assertThat(ClassUtils.forName("java.lang.String[]", classLoader)).isEqualTo(String[].class);
assertThat(ClassUtils.forName(String[].class.getName(), classLoader)).isEqualTo(String[].class);
assertThat(ClassUtils.forName(String[][].class.getName(), classLoader)).isEqualTo(String[][].class);
assertThat(ClassUtils.forName(String[][][].class.getName(), classLoader)).isEqualTo(String[][][].class);
assertThat(ClassUtils.forName("org.springframework.tests.sample.objects.TestObject", classLoader)).isEqualTo(TestObject.class);
assertThat(ClassUtils.forName("org.springframework.tests.sample.objects.TestObject[]", classLoader)).isEqualTo(TestObject[].class);
assertThat(ClassUtils.forName(TestObject[].class.getName(), classLoader)).isEqualTo(TestObject[].class);
assertThat(ClassUtils.forName("org.springframework.tests.sample.objects.TestObject[][]", classLoader)).isEqualTo(TestObject[][].class);
assertThat(ClassUtils.forName(TestObject[][].class.getName(), classLoader)).isEqualTo(TestObject[][].class);
assertThat(ClassUtils.forName("[[[S", classLoader)).isEqualTo(short[][][].class);
}
@Test
public void testForNameWithPrimitiveClasses() throws ClassNotFoundException {
assertEquals(boolean.class, ClassUtils.forName("boolean", classLoader));
assertEquals(byte.class, ClassUtils.forName("byte", classLoader));
assertEquals(char.class, ClassUtils.forName("char", classLoader));
assertEquals(short.class, ClassUtils.forName("short", classLoader));
assertEquals(int.class, ClassUtils.forName("int", classLoader));
assertEquals(long.class, ClassUtils.forName("long", classLoader));
assertEquals(float.class, ClassUtils.forName("float", classLoader));
assertEquals(double.class, ClassUtils.forName("double", classLoader));
assertEquals(void.class, ClassUtils.forName("void", classLoader));
assertThat(ClassUtils.forName("boolean", classLoader)).isEqualTo(boolean.class);
assertThat(ClassUtils.forName("byte", classLoader)).isEqualTo(byte.class);
assertThat(ClassUtils.forName("char", classLoader)).isEqualTo(char.class);
assertThat(ClassUtils.forName("short", classLoader)).isEqualTo(short.class);
assertThat(ClassUtils.forName("int", classLoader)).isEqualTo(int.class);
assertThat(ClassUtils.forName("long", classLoader)).isEqualTo(long.class);
assertThat(ClassUtils.forName("float", classLoader)).isEqualTo(float.class);
assertThat(ClassUtils.forName("double", classLoader)).isEqualTo(double.class);
assertThat(ClassUtils.forName("void", classLoader)).isEqualTo(void.class);
}
@Test
public void testForNameWithPrimitiveArrays() throws ClassNotFoundException {
assertEquals(boolean[].class, ClassUtils.forName("boolean[]", classLoader));
assertEquals(byte[].class, ClassUtils.forName("byte[]", classLoader));
assertEquals(char[].class, ClassUtils.forName("char[]", classLoader));
assertEquals(short[].class, ClassUtils.forName("short[]", classLoader));
assertEquals(int[].class, ClassUtils.forName("int[]", classLoader));
assertEquals(long[].class, ClassUtils.forName("long[]", classLoader));
assertEquals(float[].class, ClassUtils.forName("float[]", classLoader));
assertEquals(double[].class, ClassUtils.forName("double[]", classLoader));
assertThat(ClassUtils.forName("boolean[]", classLoader)).isEqualTo(boolean[].class);
assertThat(ClassUtils.forName("byte[]", classLoader)).isEqualTo(byte[].class);
assertThat(ClassUtils.forName("char[]", classLoader)).isEqualTo(char[].class);
assertThat(ClassUtils.forName("short[]", classLoader)).isEqualTo(short[].class);
assertThat(ClassUtils.forName("int[]", classLoader)).isEqualTo(int[].class);
assertThat(ClassUtils.forName("long[]", classLoader)).isEqualTo(long[].class);
assertThat(ClassUtils.forName("float[]", classLoader)).isEqualTo(float[].class);
assertThat(ClassUtils.forName("double[]", classLoader)).isEqualTo(double[].class);
}
@Test
public void testForNameWithPrimitiveArraysInternalName() throws ClassNotFoundException {
assertEquals(boolean[].class, ClassUtils.forName(boolean[].class.getName(), classLoader));
assertEquals(byte[].class, ClassUtils.forName(byte[].class.getName(), classLoader));
assertEquals(char[].class, ClassUtils.forName(char[].class.getName(), classLoader));
assertEquals(short[].class, ClassUtils.forName(short[].class.getName(), classLoader));
assertEquals(int[].class, ClassUtils.forName(int[].class.getName(), classLoader));
assertEquals(long[].class, ClassUtils.forName(long[].class.getName(), classLoader));
assertEquals(float[].class, ClassUtils.forName(float[].class.getName(), classLoader));
assertEquals(double[].class, ClassUtils.forName(double[].class.getName(), classLoader));
assertThat(ClassUtils.forName(boolean[].class.getName(), classLoader)).isEqualTo(boolean[].class);
assertThat(ClassUtils.forName(byte[].class.getName(), classLoader)).isEqualTo(byte[].class);
assertThat(ClassUtils.forName(char[].class.getName(), classLoader)).isEqualTo(char[].class);
assertThat(ClassUtils.forName(short[].class.getName(), classLoader)).isEqualTo(short[].class);
assertThat(ClassUtils.forName(int[].class.getName(), classLoader)).isEqualTo(int[].class);
assertThat(ClassUtils.forName(long[].class.getName(), classLoader)).isEqualTo(long[].class);
assertThat(ClassUtils.forName(float[].class.getName(), classLoader)).isEqualTo(float[].class);
assertThat(ClassUtils.forName(double[].class.getName(), classLoader)).isEqualTo(double[].class);
}
@Test
@@ -133,208 +129,204 @@ public class ClassUtilsTests {
Class<?> composite = ClassUtils.createCompositeInterface(
new Class<?>[] {Serializable.class, Externalizable.class}, childLoader1);
assertTrue(ClassUtils.isCacheSafe(String.class, null));
assertTrue(ClassUtils.isCacheSafe(String.class, classLoader));
assertTrue(ClassUtils.isCacheSafe(String.class, childLoader1));
assertTrue(ClassUtils.isCacheSafe(String.class, childLoader2));
assertTrue(ClassUtils.isCacheSafe(String.class, childLoader3));
assertFalse(ClassUtils.isCacheSafe(InnerClass.class, null));
assertTrue(ClassUtils.isCacheSafe(InnerClass.class, classLoader));
assertTrue(ClassUtils.isCacheSafe(InnerClass.class, childLoader1));
assertTrue(ClassUtils.isCacheSafe(InnerClass.class, childLoader2));
assertTrue(ClassUtils.isCacheSafe(InnerClass.class, childLoader3));
assertFalse(ClassUtils.isCacheSafe(composite, null));
assertFalse(ClassUtils.isCacheSafe(composite, classLoader));
assertTrue(ClassUtils.isCacheSafe(composite, childLoader1));
assertFalse(ClassUtils.isCacheSafe(composite, childLoader2));
assertTrue(ClassUtils.isCacheSafe(composite, childLoader3));
assertThat(ClassUtils.isCacheSafe(String.class, null)).isTrue();
assertThat(ClassUtils.isCacheSafe(String.class, classLoader)).isTrue();
assertThat(ClassUtils.isCacheSafe(String.class, childLoader1)).isTrue();
assertThat(ClassUtils.isCacheSafe(String.class, childLoader2)).isTrue();
assertThat(ClassUtils.isCacheSafe(String.class, childLoader3)).isTrue();
assertThat(ClassUtils.isCacheSafe(InnerClass.class, null)).isFalse();
assertThat(ClassUtils.isCacheSafe(InnerClass.class, classLoader)).isTrue();
assertThat(ClassUtils.isCacheSafe(InnerClass.class, childLoader1)).isTrue();
assertThat(ClassUtils.isCacheSafe(InnerClass.class, childLoader2)).isTrue();
assertThat(ClassUtils.isCacheSafe(InnerClass.class, childLoader3)).isTrue();
assertThat(ClassUtils.isCacheSafe(composite, null)).isFalse();
assertThat(ClassUtils.isCacheSafe(composite, classLoader)).isFalse();
assertThat(ClassUtils.isCacheSafe(composite, childLoader1)).isTrue();
assertThat(ClassUtils.isCacheSafe(composite, childLoader2)).isFalse();
assertThat(ClassUtils.isCacheSafe(composite, childLoader3)).isTrue();
}
@Test
public void testGetShortName() {
String className = ClassUtils.getShortName(getClass());
assertEquals("Class name did not match", "ClassUtilsTests", className);
assertThat(className).as("Class name did not match").isEqualTo("ClassUtilsTests");
}
@Test
public void testGetShortNameForObjectArrayClass() {
String className = ClassUtils.getShortName(Object[].class);
assertEquals("Class name did not match", "Object[]", className);
assertThat(className).as("Class name did not match").isEqualTo("Object[]");
}
@Test
public void testGetShortNameForMultiDimensionalObjectArrayClass() {
String className = ClassUtils.getShortName(Object[][].class);
assertEquals("Class name did not match", "Object[][]", className);
assertThat(className).as("Class name did not match").isEqualTo("Object[][]");
}
@Test
public void testGetShortNameForPrimitiveArrayClass() {
String className = ClassUtils.getShortName(byte[].class);
assertEquals("Class name did not match", "byte[]", className);
assertThat(className).as("Class name did not match").isEqualTo("byte[]");
}
@Test
public void testGetShortNameForMultiDimensionalPrimitiveArrayClass() {
String className = ClassUtils.getShortName(byte[][][].class);
assertEquals("Class name did not match", "byte[][][]", className);
assertThat(className).as("Class name did not match").isEqualTo("byte[][][]");
}
@Test
public void testGetShortNameForInnerClass() {
String className = ClassUtils.getShortName(InnerClass.class);
assertEquals("Class name did not match", "ClassUtilsTests.InnerClass", className);
assertThat(className).as("Class name did not match").isEqualTo("ClassUtilsTests.InnerClass");
}
@Test
public void testGetShortNameAsProperty() {
String shortName = ClassUtils.getShortNameAsProperty(this.getClass());
assertEquals("Class name did not match", "classUtilsTests", shortName);
assertThat(shortName).as("Class name did not match").isEqualTo("classUtilsTests");
}
@Test
public void testGetClassFileName() {
assertEquals("String.class", ClassUtils.getClassFileName(String.class));
assertEquals("ClassUtilsTests.class", ClassUtils.getClassFileName(getClass()));
assertThat(ClassUtils.getClassFileName(String.class)).isEqualTo("String.class");
assertThat(ClassUtils.getClassFileName(getClass())).isEqualTo("ClassUtilsTests.class");
}
@Test
public void testGetPackageName() {
assertEquals("java.lang", ClassUtils.getPackageName(String.class));
assertEquals(getClass().getPackage().getName(), ClassUtils.getPackageName(getClass()));
assertThat(ClassUtils.getPackageName(String.class)).isEqualTo("java.lang");
assertThat(ClassUtils.getPackageName(getClass())).isEqualTo(getClass().getPackage().getName());
}
@Test
public void testGetQualifiedName() {
String className = ClassUtils.getQualifiedName(getClass());
assertEquals("Class name did not match", "org.springframework.util.ClassUtilsTests", className);
assertThat(className).as("Class name did not match").isEqualTo("org.springframework.util.ClassUtilsTests");
}
@Test
public void testGetQualifiedNameForObjectArrayClass() {
String className = ClassUtils.getQualifiedName(Object[].class);
assertEquals("Class name did not match", "java.lang.Object[]", className);
assertThat(className).as("Class name did not match").isEqualTo("java.lang.Object[]");
}
@Test
public void testGetQualifiedNameForMultiDimensionalObjectArrayClass() {
String className = ClassUtils.getQualifiedName(Object[][].class);
assertEquals("Class name did not match", "java.lang.Object[][]", className);
assertThat(className).as("Class name did not match").isEqualTo("java.lang.Object[][]");
}
@Test
public void testGetQualifiedNameForPrimitiveArrayClass() {
String className = ClassUtils.getQualifiedName(byte[].class);
assertEquals("Class name did not match", "byte[]", className);
assertThat(className).as("Class name did not match").isEqualTo("byte[]");
}
@Test
public void testGetQualifiedNameForMultiDimensionalPrimitiveArrayClass() {
String className = ClassUtils.getQualifiedName(byte[][].class);
assertEquals("Class name did not match", "byte[][]", className);
assertThat(className).as("Class name did not match").isEqualTo("byte[][]");
}
@Test
public void testHasMethod() {
assertTrue(ClassUtils.hasMethod(Collection.class, "size"));
assertTrue(ClassUtils.hasMethod(Collection.class, "remove", Object.class));
assertFalse(ClassUtils.hasMethod(Collection.class, "remove"));
assertFalse(ClassUtils.hasMethod(Collection.class, "someOtherMethod"));
assertThat(ClassUtils.hasMethod(Collection.class, "size")).isTrue();
assertThat(ClassUtils.hasMethod(Collection.class, "remove", Object.class)).isTrue();
assertThat(ClassUtils.hasMethod(Collection.class, "remove")).isFalse();
assertThat(ClassUtils.hasMethod(Collection.class, "someOtherMethod")).isFalse();
}
@Test
public void testGetMethodIfAvailable() {
Method method = ClassUtils.getMethodIfAvailable(Collection.class, "size");
assertNotNull(method);
assertEquals("size", method.getName());
assertThat(method).isNotNull();
assertThat(method.getName()).isEqualTo("size");
method = ClassUtils.getMethodIfAvailable(Collection.class, "remove", Object.class);
assertNotNull(method);
assertEquals("remove", method.getName());
assertThat(method).isNotNull();
assertThat(method.getName()).isEqualTo("remove");
assertNull(ClassUtils.getMethodIfAvailable(Collection.class, "remove"));
assertNull(ClassUtils.getMethodIfAvailable(Collection.class, "someOtherMethod"));
assertThat(ClassUtils.getMethodIfAvailable(Collection.class, "remove")).isNull();
assertThat(ClassUtils.getMethodIfAvailable(Collection.class, "someOtherMethod")).isNull();
}
@Test
public void testGetMethodCountForName() {
assertEquals("Verifying number of overloaded 'print' methods for OverloadedMethodsClass.", 2,
ClassUtils.getMethodCountForName(OverloadedMethodsClass.class, "print"));
assertEquals("Verifying number of overloaded 'print' methods for SubOverloadedMethodsClass.", 4,
ClassUtils.getMethodCountForName(SubOverloadedMethodsClass.class, "print"));
assertThat(ClassUtils.getMethodCountForName(OverloadedMethodsClass.class, "print")).as("Verifying number of overloaded 'print' methods for OverloadedMethodsClass.").isEqualTo(2);
assertThat(ClassUtils.getMethodCountForName(SubOverloadedMethodsClass.class, "print")).as("Verifying number of overloaded 'print' methods for SubOverloadedMethodsClass.").isEqualTo(4);
}
@Test
public void testCountOverloadedMethods() {
assertFalse(ClassUtils.hasAtLeastOneMethodWithName(TestObject.class, "foobar"));
assertThat(ClassUtils.hasAtLeastOneMethodWithName(TestObject.class, "foobar")).isFalse();
// no args
assertTrue(ClassUtils.hasAtLeastOneMethodWithName(TestObject.class, "hashCode"));
assertThat(ClassUtils.hasAtLeastOneMethodWithName(TestObject.class, "hashCode")).isTrue();
// matches although it takes an arg
assertTrue(ClassUtils.hasAtLeastOneMethodWithName(TestObject.class, "setAge"));
assertThat(ClassUtils.hasAtLeastOneMethodWithName(TestObject.class, "setAge")).isTrue();
}
@Test
public void testNoArgsStaticMethod() throws IllegalAccessException, InvocationTargetException {
Method method = ClassUtils.getStaticMethod(InnerClass.class, "staticMethod");
method.invoke(null, (Object[]) null);
assertTrue("no argument method was not invoked.",
InnerClass.noArgCalled);
assertThat(InnerClass.noArgCalled).as("no argument method was not invoked.").isTrue();
}
@Test
public void testArgsStaticMethod() throws IllegalAccessException, InvocationTargetException {
Method method = ClassUtils.getStaticMethod(InnerClass.class, "argStaticMethod", String.class);
method.invoke(null, "test");
assertTrue("argument method was not invoked.", InnerClass.argCalled);
assertThat(InnerClass.argCalled).as("argument method was not invoked.").isTrue();
}
@Test
public void testOverloadedStaticMethod() throws IllegalAccessException, InvocationTargetException {
Method method = ClassUtils.getStaticMethod(InnerClass.class, "staticMethod", String.class);
method.invoke(null, "test");
assertTrue("argument method was not invoked.", InnerClass.overloadedCalled);
assertThat(InnerClass.overloadedCalled).as("argument method was not invoked.").isTrue();
}
@Test
public void testIsAssignable() {
assertTrue(ClassUtils.isAssignable(Object.class, Object.class));
assertTrue(ClassUtils.isAssignable(String.class, String.class));
assertTrue(ClassUtils.isAssignable(Object.class, String.class));
assertTrue(ClassUtils.isAssignable(Object.class, Integer.class));
assertTrue(ClassUtils.isAssignable(Number.class, Integer.class));
assertTrue(ClassUtils.isAssignable(Number.class, int.class));
assertTrue(ClassUtils.isAssignable(Integer.class, int.class));
assertTrue(ClassUtils.isAssignable(int.class, Integer.class));
assertFalse(ClassUtils.isAssignable(String.class, Object.class));
assertFalse(ClassUtils.isAssignable(Integer.class, Number.class));
assertFalse(ClassUtils.isAssignable(Integer.class, double.class));
assertFalse(ClassUtils.isAssignable(double.class, Integer.class));
assertThat(ClassUtils.isAssignable(Object.class, Object.class)).isTrue();
assertThat(ClassUtils.isAssignable(String.class, String.class)).isTrue();
assertThat(ClassUtils.isAssignable(Object.class, String.class)).isTrue();
assertThat(ClassUtils.isAssignable(Object.class, Integer.class)).isTrue();
assertThat(ClassUtils.isAssignable(Number.class, Integer.class)).isTrue();
assertThat(ClassUtils.isAssignable(Number.class, int.class)).isTrue();
assertThat(ClassUtils.isAssignable(Integer.class, int.class)).isTrue();
assertThat(ClassUtils.isAssignable(int.class, Integer.class)).isTrue();
assertThat(ClassUtils.isAssignable(String.class, Object.class)).isFalse();
assertThat(ClassUtils.isAssignable(Integer.class, Number.class)).isFalse();
assertThat(ClassUtils.isAssignable(Integer.class, double.class)).isFalse();
assertThat(ClassUtils.isAssignable(double.class, Integer.class)).isFalse();
}
@Test
public void testClassPackageAsResourcePath() {
String result = ClassUtils.classPackageAsResourcePath(Proxy.class);
assertEquals("java/lang/reflect", result);
assertThat(result).isEqualTo("java/lang/reflect");
}
@Test
public void testAddResourcePathToPackagePath() {
String result = "java/lang/reflect/xyzabc.xml";
assertEquals(result, ClassUtils.addResourcePathToPackagePath(Proxy.class, "xyzabc.xml"));
assertEquals(result, ClassUtils.addResourcePathToPackagePath(Proxy.class, "/xyzabc.xml"));
assertThat(ClassUtils.addResourcePathToPackagePath(Proxy.class, "xyzabc.xml")).isEqualTo(result);
assertThat(ClassUtils.addResourcePathToPackagePath(Proxy.class, "/xyzabc.xml")).isEqualTo(result);
assertEquals("java/lang/reflect/a/b/c/d.xml",
ClassUtils.addResourcePathToPackagePath(Proxy.class, "a/b/c/d.xml"));
assertThat(ClassUtils.addResourcePathToPackagePath(Proxy.class, "a/b/c/d.xml")).isEqualTo("java/lang/reflect/a/b/c/d.xml");
}
@Test
public void testGetAllInterfaces() {
DerivedTestObject testBean = new DerivedTestObject();
List<Class<?>> ifcs = Arrays.asList(ClassUtils.getAllInterfaces(testBean));
assertEquals("Correct number of interfaces", 4, ifcs.size());
assertTrue("Contains Serializable", ifcs.contains(Serializable.class));
assertTrue("Contains ITestBean", ifcs.contains(ITestObject.class));
assertTrue("Contains IOther", ifcs.contains(ITestInterface.class));
assertThat(ifcs.size()).as("Correct number of interfaces").isEqualTo(4);
assertThat(ifcs.contains(Serializable.class)).as("Contains Serializable").isTrue();
assertThat(ifcs.contains(ITestObject.class)).as("Contains ITestBean").isTrue();
assertThat(ifcs.contains(ITestInterface.class)).as("Contains IOther").isTrue();
}
@Test
@@ -342,50 +334,50 @@ public class ClassUtilsTests {
List<Class<?>> ifcs = new LinkedList<>();
ifcs.add(Serializable.class);
ifcs.add(Runnable.class);
assertEquals("[interface java.io.Serializable, interface java.lang.Runnable]", ifcs.toString());
assertEquals("[java.io.Serializable, java.lang.Runnable]", ClassUtils.classNamesToString(ifcs));
assertThat(ifcs.toString()).isEqualTo("[interface java.io.Serializable, interface java.lang.Runnable]");
assertThat(ClassUtils.classNamesToString(ifcs)).isEqualTo("[java.io.Serializable, java.lang.Runnable]");
List<Class<?>> classes = new LinkedList<>();
classes.add(LinkedList.class);
classes.add(Integer.class);
assertEquals("[class java.util.LinkedList, class java.lang.Integer]", classes.toString());
assertEquals("[java.util.LinkedList, java.lang.Integer]", ClassUtils.classNamesToString(classes));
assertThat(classes.toString()).isEqualTo("[class java.util.LinkedList, class java.lang.Integer]");
assertThat(ClassUtils.classNamesToString(classes)).isEqualTo("[java.util.LinkedList, java.lang.Integer]");
assertEquals("[interface java.util.List]", Collections.singletonList(List.class).toString());
assertEquals("[java.util.List]", ClassUtils.classNamesToString(List.class));
assertThat(Collections.singletonList(List.class).toString()).isEqualTo("[interface java.util.List]");
assertThat(ClassUtils.classNamesToString(List.class)).isEqualTo("[java.util.List]");
assertEquals("[]", Collections.EMPTY_LIST.toString());
assertEquals("[]", ClassUtils.classNamesToString(Collections.emptyList()));
assertThat(Collections.EMPTY_LIST.toString()).isEqualTo("[]");
assertThat(ClassUtils.classNamesToString(Collections.emptyList())).isEqualTo("[]");
}
@Test
public void testDetermineCommonAncestor() {
assertEquals(Number.class, ClassUtils.determineCommonAncestor(Integer.class, Number.class));
assertEquals(Number.class, ClassUtils.determineCommonAncestor(Number.class, Integer.class));
assertEquals(Number.class, ClassUtils.determineCommonAncestor(Number.class, null));
assertEquals(Integer.class, ClassUtils.determineCommonAncestor(null, Integer.class));
assertEquals(Integer.class, ClassUtils.determineCommonAncestor(Integer.class, Integer.class));
assertThat(ClassUtils.determineCommonAncestor(Integer.class, Number.class)).isEqualTo(Number.class);
assertThat(ClassUtils.determineCommonAncestor(Number.class, Integer.class)).isEqualTo(Number.class);
assertThat(ClassUtils.determineCommonAncestor(Number.class, null)).isEqualTo(Number.class);
assertThat(ClassUtils.determineCommonAncestor(null, Integer.class)).isEqualTo(Integer.class);
assertThat(ClassUtils.determineCommonAncestor(Integer.class, Integer.class)).isEqualTo(Integer.class);
assertEquals(Number.class, ClassUtils.determineCommonAncestor(Integer.class, Float.class));
assertEquals(Number.class, ClassUtils.determineCommonAncestor(Float.class, Integer.class));
assertNull(ClassUtils.determineCommonAncestor(Integer.class, String.class));
assertNull(ClassUtils.determineCommonAncestor(String.class, Integer.class));
assertThat(ClassUtils.determineCommonAncestor(Integer.class, Float.class)).isEqualTo(Number.class);
assertThat(ClassUtils.determineCommonAncestor(Float.class, Integer.class)).isEqualTo(Number.class);
assertThat(ClassUtils.determineCommonAncestor(Integer.class, String.class)).isNull();
assertThat(ClassUtils.determineCommonAncestor(String.class, Integer.class)).isNull();
assertEquals(Collection.class, ClassUtils.determineCommonAncestor(List.class, Collection.class));
assertEquals(Collection.class, ClassUtils.determineCommonAncestor(Collection.class, List.class));
assertEquals(Collection.class, ClassUtils.determineCommonAncestor(Collection.class, null));
assertEquals(List.class, ClassUtils.determineCommonAncestor(null, List.class));
assertEquals(List.class, ClassUtils.determineCommonAncestor(List.class, List.class));
assertThat(ClassUtils.determineCommonAncestor(List.class, Collection.class)).isEqualTo(Collection.class);
assertThat(ClassUtils.determineCommonAncestor(Collection.class, List.class)).isEqualTo(Collection.class);
assertThat(ClassUtils.determineCommonAncestor(Collection.class, null)).isEqualTo(Collection.class);
assertThat(ClassUtils.determineCommonAncestor(null, List.class)).isEqualTo(List.class);
assertThat(ClassUtils.determineCommonAncestor(List.class, List.class)).isEqualTo(List.class);
assertNull(ClassUtils.determineCommonAncestor(List.class, Set.class));
assertNull(ClassUtils.determineCommonAncestor(Set.class, List.class));
assertNull(ClassUtils.determineCommonAncestor(List.class, Runnable.class));
assertNull(ClassUtils.determineCommonAncestor(Runnable.class, List.class));
assertThat(ClassUtils.determineCommonAncestor(List.class, Set.class)).isNull();
assertThat(ClassUtils.determineCommonAncestor(Set.class, List.class)).isNull();
assertThat(ClassUtils.determineCommonAncestor(List.class, Runnable.class)).isNull();
assertThat(ClassUtils.determineCommonAncestor(Runnable.class, List.class)).isNull();
assertEquals(List.class, ClassUtils.determineCommonAncestor(List.class, ArrayList.class));
assertEquals(List.class, ClassUtils.determineCommonAncestor(ArrayList.class, List.class));
assertNull(ClassUtils.determineCommonAncestor(List.class, String.class));
assertNull(ClassUtils.determineCommonAncestor(String.class, List.class));
assertThat(ClassUtils.determineCommonAncestor(List.class, ArrayList.class)).isEqualTo(List.class);
assertThat(ClassUtils.determineCommonAncestor(ArrayList.class, List.class)).isEqualTo(List.class);
assertThat(ClassUtils.determineCommonAncestor(List.class, String.class)).isNull();
assertThat(ClassUtils.determineCommonAncestor(String.class, List.class)).isNull();
}

View File

@@ -30,9 +30,7 @@ import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Harrop
@@ -43,18 +41,18 @@ public class CollectionUtilsTests {
@Test
public void testIsEmpty() {
assertTrue(CollectionUtils.isEmpty((Set<Object>) null));
assertTrue(CollectionUtils.isEmpty((Map<String, String>) null));
assertTrue(CollectionUtils.isEmpty(new HashMap<String, String>()));
assertTrue(CollectionUtils.isEmpty(new HashSet<>()));
assertThat(CollectionUtils.isEmpty((Set<Object>) null)).isTrue();
assertThat(CollectionUtils.isEmpty((Map<String, String>) null)).isTrue();
assertThat(CollectionUtils.isEmpty(new HashMap<String, String>())).isTrue();
assertThat(CollectionUtils.isEmpty(new HashSet<>())).isTrue();
List<Object> list = new LinkedList<>();
list.add(new Object());
assertFalse(CollectionUtils.isEmpty(list));
assertThat(CollectionUtils.isEmpty(list)).isFalse();
Map<String, String> map = new HashMap<>();
map.put("foo", "bar");
assertFalse(CollectionUtils.isEmpty(map));
assertThat(CollectionUtils.isEmpty(map)).isFalse();
}
@Test
@@ -64,9 +62,9 @@ public class CollectionUtilsTests {
list.add("value3");
CollectionUtils.mergeArrayIntoCollection(arr, list);
assertEquals("value3", list.get(0));
assertEquals("value1", list.get(1));
assertEquals("value2", list.get(2));
assertThat(list.get(0)).isEqualTo("value3");
assertThat(list.get(1)).isEqualTo("value1");
assertThat(list.get(2)).isEqualTo("value2");
}
@Test
@@ -76,9 +74,9 @@ public class CollectionUtilsTests {
list.add(Integer.valueOf(3));
CollectionUtils.mergeArrayIntoCollection(arr, list);
assertEquals(Integer.valueOf(3), list.get(0));
assertEquals(Integer.valueOf(1), list.get(1));
assertEquals(Integer.valueOf(2), list.get(2));
assertThat(list.get(0)).isEqualTo(Integer.valueOf(3));
assertThat(list.get(1)).isEqualTo(Integer.valueOf(1));
assertThat(list.get(2)).isEqualTo(Integer.valueOf(2));
}
@Test
@@ -89,30 +87,30 @@ public class CollectionUtilsTests {
props.setProperty("prop2", "value2");
props.put("prop3", Integer.valueOf(3));
Map<String, String> map = new HashMap<>();
Map<String, Object> map = new HashMap<>();
map.put("prop4", "value4");
CollectionUtils.mergePropertiesIntoMap(props, map);
assertEquals("value1", map.get("prop1"));
assertEquals("value2", map.get("prop2"));
assertEquals(Integer.valueOf(3), map.get("prop3"));
assertEquals("value4", map.get("prop4"));
assertThat(map.get("prop1")).isEqualTo("value1");
assertThat(map.get("prop2")).isEqualTo("value2");
assertThat(map.get("prop3")).isEqualTo(Integer.valueOf(3));
assertThat(map.get("prop4")).isEqualTo("value4");
}
@Test
public void testContains() {
assertFalse(CollectionUtils.contains((Iterator<String>) null, "myElement"));
assertFalse(CollectionUtils.contains((Enumeration<String>) null, "myElement"));
assertFalse(CollectionUtils.contains(new LinkedList<String>().iterator(), "myElement"));
assertFalse(CollectionUtils.contains(new Hashtable<String, Object>().keys(), "myElement"));
assertThat(CollectionUtils.contains((Iterator<String>) null, "myElement")).isFalse();
assertThat(CollectionUtils.contains((Enumeration<String>) null, "myElement")).isFalse();
assertThat(CollectionUtils.contains(new LinkedList<String>().iterator(), "myElement")).isFalse();
assertThat(CollectionUtils.contains(new Hashtable<String, Object>().keys(), "myElement")).isFalse();
List<String> list = new LinkedList<>();
list.add("myElement");
assertTrue(CollectionUtils.contains(list.iterator(), "myElement"));
assertThat(CollectionUtils.contains(list.iterator(), "myElement")).isTrue();
Hashtable<String, String> ht = new Hashtable<>();
ht.put("myElement", "myValue");
assertTrue(CollectionUtils.contains(ht.keys(), "myElement"));
assertThat(CollectionUtils.contains(ht.keys(), "myElement")).isTrue();
}
@Test
@@ -127,25 +125,23 @@ public class CollectionUtilsTests {
candidates.add("def");
candidates.add("abc");
assertTrue(CollectionUtils.containsAny(source, candidates));
assertThat(CollectionUtils.containsAny(source, candidates)).isTrue();
candidates.remove("def");
assertTrue(CollectionUtils.containsAny(source, candidates));
assertThat(CollectionUtils.containsAny(source, candidates)).isTrue();
candidates.remove("abc");
assertFalse(CollectionUtils.containsAny(source, candidates));
assertThat(CollectionUtils.containsAny(source, candidates)).isFalse();
}
@Test
public void testContainsInstanceWithNullCollection() throws Exception {
assertFalse("Must return false if supplied Collection argument is null",
CollectionUtils.containsInstance(null, this));
assertThat(CollectionUtils.containsInstance(null, this)).as("Must return false if supplied Collection argument is null").isFalse();
}
@Test
public void testContainsInstanceWithInstancesThatAreEqualButDistinct() throws Exception {
List<Instance> list = new ArrayList<>();
list.add(new Instance("fiona"));
assertFalse("Must return false if instance is not in the supplied Collection argument",
CollectionUtils.containsInstance(list, new Instance("fiona")));
assertThat(CollectionUtils.containsInstance(list, new Instance("fiona"))).as("Must return false if instance is not in the supplied Collection argument").isFalse();
}
@Test
@@ -154,8 +150,7 @@ public class CollectionUtilsTests {
list.add(new Instance("apple"));
Instance instance = new Instance("fiona");
list.add(instance);
assertTrue("Must return true if instance is in the supplied Collection argument",
CollectionUtils.containsInstance(list, instance));
assertThat(CollectionUtils.containsInstance(list, instance)).as("Must return true if instance is in the supplied Collection argument").isTrue();
}
@Test
@@ -163,8 +158,7 @@ public class CollectionUtilsTests {
List<Instance> list = new ArrayList<>();
list.add(new Instance("apple"));
list.add(new Instance("fiona"));
assertFalse("Must return false if null instance is supplied",
CollectionUtils.containsInstance(list, null));
assertThat(CollectionUtils.containsInstance(list, null)).as("Must return false if null instance is supplied").isFalse();
}
@Test
@@ -179,7 +173,7 @@ public class CollectionUtilsTests {
candidates.add("def");
candidates.add("abc");
assertEquals("def", CollectionUtils.findFirstMatch(source, candidates));
assertThat(CollectionUtils.findFirstMatch(source, candidates)).isEqualTo("def");
}
@Test
@@ -187,33 +181,33 @@ public class CollectionUtilsTests {
List<String> list = new LinkedList<>();
list.add("myElement");
list.add("myOtherElement");
assertFalse(CollectionUtils.hasUniqueObject(list));
assertThat(CollectionUtils.hasUniqueObject(list)).isFalse();
list = new LinkedList<>();
list.add("myElement");
assertTrue(CollectionUtils.hasUniqueObject(list));
assertThat(CollectionUtils.hasUniqueObject(list)).isTrue();
list = new LinkedList<>();
list.add("myElement");
list.add(null);
assertFalse(CollectionUtils.hasUniqueObject(list));
assertThat(CollectionUtils.hasUniqueObject(list)).isFalse();
list = new LinkedList<>();
list.add(null);
list.add("myElement");
assertFalse(CollectionUtils.hasUniqueObject(list));
assertThat(CollectionUtils.hasUniqueObject(list)).isFalse();
list = new LinkedList<>();
list.add(null);
list.add(null);
assertTrue(CollectionUtils.hasUniqueObject(list));
assertThat(CollectionUtils.hasUniqueObject(list)).isTrue();
list = new LinkedList<>();
list.add(null);
assertTrue(CollectionUtils.hasUniqueObject(list));
assertThat(CollectionUtils.hasUniqueObject(list)).isTrue();
list = new LinkedList<>();
assertFalse(CollectionUtils.hasUniqueObject(list));
assertThat(CollectionUtils.hasUniqueObject(list)).isFalse();
}

View File

@@ -23,12 +23,10 @@ import java.util.NoSuchElementException;
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.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
@@ -42,7 +40,7 @@ public class CompositeIteratorTests {
@Test
public void testNoIterators() {
CompositeIterator<String> it = new CompositeIterator<>();
assertFalse(it.hasNext());
assertThat(it.hasNext()).isFalse();
assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(
it::next);
}
@@ -52,10 +50,10 @@ public class CompositeIteratorTests {
CompositeIterator<String> it = new CompositeIterator<>();
it.add(Arrays.asList("0", "1").iterator());
for (int i = 0; i < 2; i++) {
assertTrue(it.hasNext());
assertEquals(String.valueOf(i), it.next());
assertThat(it.hasNext()).isTrue();
assertThat(it.next()).isEqualTo(String.valueOf(i));
}
assertFalse(it.hasNext());
assertThat(it.hasNext()).isFalse();
assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(
it::next);
}
@@ -67,10 +65,10 @@ public class CompositeIteratorTests {
it.add(Arrays.asList("2").iterator());
it.add(Arrays.asList("3", "4").iterator());
for (int i = 0; i < 5; i++) {
assertTrue(it.hasNext());
assertEquals(String.valueOf(i), it.next());
assertThat(it.hasNext()).isTrue();
assertThat(it.next()).isEqualTo(String.valueOf(i));
}
assertFalse(it.hasNext());
assertThat(it.hasNext()).isFalse();
assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(
it::next);

View File

@@ -41,7 +41,6 @@ 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.junit.Assert.assertFalse;
/**
* Tests for {@link ConcurrentReferenceHashMap}.
@@ -278,7 +277,7 @@ public class ConcurrentReferenceHashMapTests {
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.containsKey(123)).isFalse();
assertThat(this.map.isEmpty()).isTrue();
}
@@ -288,7 +287,7 @@ public class ConcurrentReferenceHashMapTests {
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.containsKey(123)).isFalse();
assertThat(this.map.isEmpty()).isTrue();
}

View File

@@ -23,8 +23,7 @@ import java.io.UnsupportedEncodingException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Arjen Poutsma
@@ -47,10 +46,10 @@ public class DigestUtilsTests {
{-0x4f, 0xa, -0x73, -0x4f, 0x64, -0x20, 0x75, 0x41, 0x5, -0x49, -0x57, -0x65, -0x19, 0x2e, 0x3f, -0x1b};
byte[] result = DigestUtils.md5Digest(bytes);
assertArrayEquals("Invalid hash", expected, result);
assertThat(result).as("Invalid hash").isEqualTo(expected);
result = DigestUtils.md5Digest(new ByteArrayInputStream(bytes));
assertArrayEquals("Invalid hash", expected, result);
assertThat(result).as("Invalid hash").isEqualTo(expected);
}
@Test
@@ -58,10 +57,10 @@ public class DigestUtilsTests {
String expected = "b10a8db164e0754105b7a99be72e3fe5";
String hash = DigestUtils.md5DigestAsHex(bytes);
assertEquals("Invalid hash", expected, hash);
assertThat(hash).as("Invalid hash").isEqualTo(expected);
hash = DigestUtils.md5DigestAsHex(new ByteArrayInputStream(bytes));
assertEquals("Invalid hash", expected, hash);
assertThat(hash).as("Invalid hash").isEqualTo(expected);
}
@Test
@@ -70,11 +69,11 @@ public class DigestUtilsTests {
StringBuilder builder = new StringBuilder();
DigestUtils.appendMd5DigestAsHex(bytes, builder);
assertEquals("Invalid hash", expected, builder.toString());
assertThat(builder.toString()).as("Invalid hash").isEqualTo(expected);
builder = new StringBuilder();
DigestUtils.appendMd5DigestAsHex(new ByteArrayInputStream(bytes), builder);
assertEquals("Invalid hash", expected, builder.toString());
assertThat(builder.toString()).as("Invalid hash").isEqualTo(expected);
}
}

View File

@@ -19,7 +19,7 @@ package org.springframework.util;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Stephane Nicoll
@@ -30,8 +30,8 @@ public class ExceptionTypeFilterTests {
public void subClassMatch() {
ExceptionTypeFilter filter = new ExceptionTypeFilter(
asList(RuntimeException.class), null, true);
assertTrue(filter.match(RuntimeException.class));
assertTrue(filter.match(IllegalStateException.class));
assertThat(filter.match(RuntimeException.class)).isTrue();
assertThat(filter.match(IllegalStateException.class)).isTrue();
}
}

View File

@@ -21,8 +21,8 @@ import org.junit.Test;
import org.springframework.util.backoff.BackOffExecution;
import org.springframework.util.backoff.ExponentialBackOff;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
/**
*
@@ -34,19 +34,19 @@ public class ExponentialBackOffTests {
public void defaultInstance() {
ExponentialBackOff backOff = new ExponentialBackOff();
BackOffExecution execution = backOff.start();
assertEquals(2000L, execution.nextBackOff());
assertEquals(3000L, execution.nextBackOff());
assertEquals(4500L, execution.nextBackOff());
assertThat(execution.nextBackOff()).isEqualTo(2000L);
assertThat(execution.nextBackOff()).isEqualTo(3000L);
assertThat(execution.nextBackOff()).isEqualTo(4500L);
}
@Test
public void simpleIncrease() {
ExponentialBackOff backOff = new ExponentialBackOff(100L, 2.0);
BackOffExecution execution = backOff.start();
assertEquals(100L, execution.nextBackOff());
assertEquals(200L, execution.nextBackOff());
assertEquals(400L, execution.nextBackOff());
assertEquals(800L, execution.nextBackOff());
assertThat(execution.nextBackOff()).isEqualTo(100L);
assertThat(execution.nextBackOff()).isEqualTo(200L);
assertThat(execution.nextBackOff()).isEqualTo(400L);
assertThat(execution.nextBackOff()).isEqualTo(800L);
}
@Test
@@ -55,10 +55,10 @@ public class ExponentialBackOffTests {
backOff.setMaxElapsedTime(300L);
BackOffExecution execution = backOff.start();
assertEquals(100L, execution.nextBackOff());
assertEquals(100L, execution.nextBackOff());
assertEquals(100L, execution.nextBackOff());
assertEquals(BackOffExecution.STOP, execution.nextBackOff());
assertThat(execution.nextBackOff()).isEqualTo(100L);
assertThat(execution.nextBackOff()).isEqualTo(100L);
assertThat(execution.nextBackOff()).isEqualTo(100L);
assertThat(execution.nextBackOff()).isEqualTo(BackOffExecution.STOP);
}
@Test
@@ -67,10 +67,11 @@ public class ExponentialBackOffTests {
backOff.setMaxInterval(4000L);
BackOffExecution execution = backOff.start();
assertEquals(2000L, execution.nextBackOff());
assertEquals(4000L, execution.nextBackOff());
assertEquals(4000L, execution.nextBackOff()); // max reached
assertEquals(4000L, execution.nextBackOff());
assertThat(execution.nextBackOff()).isEqualTo(2000L);
assertThat(execution.nextBackOff()).isEqualTo(4000L);
// max reached
assertThat(execution.nextBackOff()).isEqualTo(4000L);
assertThat(execution.nextBackOff()).isEqualTo(4000L);
}
@Test
@@ -79,9 +80,10 @@ public class ExponentialBackOffTests {
backOff.setMaxElapsedTime(4000L);
BackOffExecution execution = backOff.start();
assertEquals(2000L, execution.nextBackOff());
assertEquals(4000L, execution.nextBackOff());
assertEquals(BackOffExecution.STOP, execution.nextBackOff()); // > 4 sec wait in total
assertThat(execution.nextBackOff()).isEqualTo(2000L);
assertThat(execution.nextBackOff()).isEqualTo(4000L);
// > 4 sec wait in total
assertThat(execution.nextBackOff()).isEqualTo(BackOffExecution.STOP);
}
@Test
@@ -94,12 +96,12 @@ public class ExponentialBackOffTests {
BackOffExecution execution = backOff.start();
BackOffExecution execution2 = backOff.start();
assertEquals(2000L, execution.nextBackOff());
assertEquals(2000L, execution2.nextBackOff());
assertEquals(4000L, execution.nextBackOff());
assertEquals(4000L, execution2.nextBackOff());
assertEquals(BackOffExecution.STOP, execution.nextBackOff());
assertEquals(BackOffExecution.STOP, execution2.nextBackOff());
assertThat(execution.nextBackOff()).isEqualTo(2000L);
assertThat(execution2.nextBackOff()).isEqualTo(2000L);
assertThat(execution.nextBackOff()).isEqualTo(4000L);
assertThat(execution2.nextBackOff()).isEqualTo(4000L);
assertThat(execution.nextBackOff()).isEqualTo(BackOffExecution.STOP);
assertThat(execution2.nextBackOff()).isEqualTo(BackOffExecution.STOP);
}
@Test
@@ -115,19 +117,19 @@ public class ExponentialBackOffTests {
backOff.setMaxInterval(50L);
BackOffExecution execution = backOff.start();
assertEquals(50L, execution.nextBackOff());
assertEquals(50L, execution.nextBackOff());
assertThat(execution.nextBackOff()).isEqualTo(50L);
assertThat(execution.nextBackOff()).isEqualTo(50L);
}
@Test
public void toStringContent() {
ExponentialBackOff backOff = new ExponentialBackOff(2000L, 2.0);
BackOffExecution execution = backOff.start();
assertEquals("ExponentialBackOff{currentInterval=n/a, multiplier=2.0}", execution.toString());
assertThat(execution.toString()).isEqualTo("ExponentialBackOff{currentInterval=n/a, multiplier=2.0}");
execution.nextBackOff();
assertEquals("ExponentialBackOff{currentInterval=2000ms, multiplier=2.0}", execution.toString());
assertThat(execution.toString()).isEqualTo("ExponentialBackOff{currentInterval=2000ms, multiplier=2.0}");
execution.nextBackOff();
assertEquals("ExponentialBackOff{currentInterval=4000ms, multiplier=2.0}", execution.toString());
assertThat(execution.toString()).isEqualTo("ExponentialBackOff{currentInterval=4000ms, multiplier=2.0}");
}
}

View File

@@ -24,12 +24,9 @@ import java.nio.charset.StandardCharsets;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
/**
* Test suite for {@link FastByteArrayOutputStream}.
@@ -48,7 +45,7 @@ public class FastByteArrayOutputStreamTests {
@Test
public void size() throws Exception {
this.os.write(this.helloBytes);
assertEquals(this.os.size(), this.helloBytes.length);
assertThat(this.helloBytes.length).isEqualTo(this.os.size());
}
@Test
@@ -57,7 +54,7 @@ public class FastByteArrayOutputStreamTests {
int sizeBefore = this.os.size();
this.os.resize(64);
assertByteArrayEqualsString(this.os);
assertEquals(sizeBefore, this.os.size());
assertThat(this.os.size()).isEqualTo(sizeBefore);
}
@Test
@@ -66,8 +63,8 @@ public class FastByteArrayOutputStreamTests {
for (int i = 0; i < 10; i++) {
this.os.write(1);
}
assertEquals(10, this.os.size());
assertArrayEquals(this.os.toByteArray(), new byte[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1});
assertThat(this.os.size()).isEqualTo(10);
assertThat(new byte[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}).isEqualTo(this.os.toByteArray());
}
@Test
@@ -81,7 +78,7 @@ public class FastByteArrayOutputStreamTests {
this.os.write(this.helloBytes);
assertByteArrayEqualsString(this.os);
this.os.reset();
assertEquals(0, this.os.size());
assertThat(this.os.size()).isEqualTo(0);
this.os.write(this.helloBytes);
assertByteArrayEqualsString(this.os);
}
@@ -97,8 +94,8 @@ public class FastByteArrayOutputStreamTests {
public void toByteArrayUnsafe() throws Exception {
this.os.write(this.helloBytes);
assertByteArrayEqualsString(this.os);
assertSame(this.os.toByteArrayUnsafe(), this.os.toByteArrayUnsafe());
assertArrayEquals(this.os.toByteArray(), this.helloBytes);
assertThat(this.os.toByteArrayUnsafe()).isSameAs(this.os.toByteArrayUnsafe());
assertThat(this.helloBytes).isEqualTo(this.os.toByteArray());
}
@Test
@@ -107,7 +104,7 @@ public class FastByteArrayOutputStreamTests {
assertByteArrayEqualsString(this.os);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
this.os.writeTo(baos);
assertArrayEquals(baos.toByteArray(), this.helloBytes);
assertThat(this.helloBytes).isEqualTo(baos.toByteArray());
}
@Test
@@ -120,23 +117,23 @@ public class FastByteArrayOutputStreamTests {
@Test
public void getInputStream() throws Exception {
this.os.write(this.helloBytes);
assertNotNull(this.os.getInputStream());
assertThat(this.os.getInputStream()).isNotNull();
}
@Test
public void getInputStreamAvailable() throws Exception {
this.os.write(this.helloBytes);
assertEquals(this.os.getInputStream().available(), this.helloBytes.length);
assertThat(this.helloBytes.length).isEqualTo(this.os.getInputStream().available());
}
@Test
public void getInputStreamRead() throws Exception {
this.os.write(this.helloBytes);
InputStream inputStream = this.os.getInputStream();
assertEquals(inputStream.read(), this.helloBytes[0]);
assertEquals(inputStream.read(), this.helloBytes[1]);
assertEquals(inputStream.read(), this.helloBytes[2]);
assertEquals(inputStream.read(), this.helloBytes[3]);
assertThat(this.helloBytes[0]).isEqualTo((byte) inputStream.read());
assertThat(this.helloBytes[1]).isEqualTo((byte) inputStream.read());
assertThat(this.helloBytes[2]).isEqualTo((byte) inputStream.read());
assertThat(this.helloBytes[3]).isEqualTo((byte) inputStream.read());
}
@Test
@@ -145,7 +142,7 @@ public class FastByteArrayOutputStreamTests {
this.os.write(bytes);
InputStream inputStream = this.os.getInputStream();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
assertEquals(bais.read(), inputStream.read());
assertThat(inputStream.read()).isEqualTo(bais.read());
}
@Test
@@ -154,9 +151,9 @@ public class FastByteArrayOutputStreamTests {
InputStream inputStream = this.os.getInputStream();
byte[] actual = new byte[inputStream.available()];
int bytesRead = inputStream.read(actual);
assertEquals(this.helloBytes.length, bytesRead);
assertArrayEquals(this.helloBytes, actual);
assertEquals(0, inputStream.available());
assertThat(bytesRead).isEqualTo(this.helloBytes.length);
assertThat(actual).isEqualTo(this.helloBytes);
assertThat(inputStream.available()).isEqualTo(0);
}
@Test
@@ -165,30 +162,30 @@ public class FastByteArrayOutputStreamTests {
InputStream inputStream = os.getInputStream();
byte[] actual = new byte[inputStream.available() + 1];
int bytesRead = inputStream.read(actual);
assertEquals(this.helloBytes.length, bytesRead);
assertThat(bytesRead).isEqualTo(this.helloBytes.length);
for (int i = 0; i < bytesRead; i++) {
assertEquals(this.helloBytes[i], actual[i]);
assertThat(actual[i]).isEqualTo(this.helloBytes[i]);
}
assertEquals(0, actual[this.helloBytes.length]);
assertEquals(0, inputStream.available());
assertThat(actual[this.helloBytes.length]).isEqualTo((byte) 0);
assertThat(inputStream.available()).isEqualTo(0);
}
@Test
public void getInputStreamSkip() throws Exception {
this.os.write(this.helloBytes);
InputStream inputStream = this.os.getInputStream();
assertEquals(inputStream.read(), this.helloBytes[0]);
assertEquals(1, inputStream.skip(1));
assertEquals(inputStream.read(), this.helloBytes[2]);
assertEquals(this.helloBytes.length - 3, inputStream.available());
assertThat(this.helloBytes[0]).isEqualTo((byte) inputStream.read());
assertThat(inputStream.skip(1)).isEqualTo(1);
assertThat(this.helloBytes[2]).isEqualTo((byte) inputStream.read());
assertThat(inputStream.available()).isEqualTo((this.helloBytes.length - 3));
}
@Test
public void getInputStreamSkipAll() throws Exception {
this.os.write(this.helloBytes);
InputStream inputStream = this.os.getInputStream();
assertEquals(inputStream.skip(1000), this.helloBytes.length);
assertEquals(0, inputStream.available());
assertThat(this.helloBytes.length).isEqualTo(inputStream.skip(1000));
assertThat(inputStream.available()).isEqualTo(0);
}
@Test
@@ -199,7 +196,7 @@ public class FastByteArrayOutputStreamTests {
DigestUtils.appendMd5DigestAsHex(inputStream, builder);
builder.append("\"");
String actual = builder.toString();
assertEquals("\"0b10a8db164e0754105b7a99be72e3fe5\"", actual);
assertThat(actual).isEqualTo("\"0b10a8db164e0754105b7a99be72e3fe5\"");
}
@Test
@@ -213,12 +210,12 @@ public class FastByteArrayOutputStreamTests {
DigestUtils.appendMd5DigestAsHex(inputStream, builder);
builder.append("\"");
String actual = builder.toString();
assertEquals("\"06225ca1e4533354c516e74512065331d\"", actual);
assertThat(actual).isEqualTo("\"06225ca1e4533354c516e74512065331d\"");
}
private void assertByteArrayEqualsString(FastByteArrayOutputStream actual) {
assertArrayEquals(this.helloBytes, actual.toByteArray());
assertThat(actual.toByteArray()).isEqualTo(this.helloBytes);
}
}

View File

@@ -25,8 +25,7 @@ import java.util.Arrays;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for the FileCopyUtils class.
@@ -42,8 +41,8 @@ public class FileCopyUtilsTests {
ByteArrayInputStream in = new ByteArrayInputStream(content);
ByteArrayOutputStream out = new ByteArrayOutputStream(content.length);
int count = FileCopyUtils.copy(in, out);
assertEquals(content.length, count);
assertTrue(Arrays.equals(content, out.toByteArray()));
assertThat(count).isEqualTo(content.length);
assertThat(Arrays.equals(content, out.toByteArray())).isTrue();
}
@Test
@@ -51,7 +50,7 @@ public class FileCopyUtilsTests {
byte[] content = "content".getBytes();
ByteArrayOutputStream out = new ByteArrayOutputStream(content.length);
FileCopyUtils.copy(content, out);
assertTrue(Arrays.equals(content, out.toByteArray()));
assertThat(Arrays.equals(content, out.toByteArray())).isTrue();
}
@Test
@@ -59,7 +58,7 @@ public class FileCopyUtilsTests {
byte[] content = "content".getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(content);
byte[] result = FileCopyUtils.copyToByteArray(in);
assertTrue(Arrays.equals(content, result));
assertThat(Arrays.equals(content, result)).isTrue();
}
@Test
@@ -68,8 +67,8 @@ public class FileCopyUtilsTests {
StringReader in = new StringReader(content);
StringWriter out = new StringWriter();
int count = FileCopyUtils.copy(in, out);
assertEquals(content.length(), count);
assertEquals(content, out.toString());
assertThat(count).isEqualTo(content.length());
assertThat(out.toString()).isEqualTo(content);
}
@Test
@@ -77,7 +76,7 @@ public class FileCopyUtilsTests {
String content = "content";
StringWriter out = new StringWriter();
FileCopyUtils.copy(content, out);
assertEquals(content, out.toString());
assertThat(out.toString()).isEqualTo(content);
}
@Test
@@ -85,7 +84,7 @@ public class FileCopyUtilsTests {
String content = "content";
StringReader in = new StringReader(content);
String result = FileCopyUtils.copyToString(in);
assertEquals(content, result);
assertThat(result).isEqualTo(content);
}
}

View File

@@ -21,8 +21,7 @@ import java.io.File;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Harrop
@@ -40,17 +39,17 @@ public class FileSystemUtilsTests {
File bar = new File(child, "bar.txt");
bar.createNewFile();
assertTrue(root.exists());
assertTrue(child.exists());
assertTrue(grandchild.exists());
assertTrue(bar.exists());
assertThat(root.exists()).isTrue();
assertThat(child.exists()).isTrue();
assertThat(grandchild.exists()).isTrue();
assertThat(bar.exists()).isTrue();
FileSystemUtils.deleteRecursively(root);
assertFalse(root.exists());
assertFalse(child.exists());
assertFalse(grandchild.exists());
assertFalse(bar.exists());
assertThat(root.exists()).isFalse();
assertThat(child.exists()).isFalse();
assertThat(grandchild.exists()).isFalse();
assertThat(bar.exists()).isFalse();
}
@Test
@@ -64,19 +63,19 @@ public class FileSystemUtilsTests {
File bar = new File(child, "bar.txt");
bar.createNewFile();
assertTrue(src.exists());
assertTrue(child.exists());
assertTrue(grandchild.exists());
assertTrue(bar.exists());
assertThat(src.exists()).isTrue();
assertThat(child.exists()).isTrue();
assertThat(grandchild.exists()).isTrue();
assertThat(bar.exists()).isTrue();
File dest = new File("./dest");
FileSystemUtils.copyRecursively(src, dest);
assertTrue(dest.exists());
assertTrue(new File(dest, child.getName()).exists());
assertThat(dest.exists()).isTrue();
assertThat(new File(dest, child.getName()).exists()).isTrue();
FileSystemUtils.deleteRecursively(src);
assertFalse(src.exists());
assertThat(src.exists()).isFalse();
}

View File

@@ -21,7 +21,7 @@ import org.junit.Test;
import org.springframework.util.backoff.BackOffExecution;
import org.springframework.util.backoff.FixedBackOff;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Stephane Nicoll
@@ -33,7 +33,7 @@ public class FixedBackOffTests {
FixedBackOff backOff = new FixedBackOff();
BackOffExecution execution = backOff.start();
for (int i = 0; i < 100; i++) {
assertEquals(FixedBackOff.DEFAULT_INTERVAL, execution.nextBackOff());
assertThat(execution.nextBackOff()).isEqualTo(FixedBackOff.DEFAULT_INTERVAL);
}
}
@@ -41,16 +41,16 @@ public class FixedBackOffTests {
public void noAttemptAtAll() {
FixedBackOff backOff = new FixedBackOff(100L, 0L);
BackOffExecution execution = backOff.start();
assertEquals(BackOffExecution.STOP, execution.nextBackOff());
assertThat(execution.nextBackOff()).isEqualTo(BackOffExecution.STOP);
}
@Test
public void maxAttemptsReached() {
FixedBackOff backOff = new FixedBackOff(200L, 2);
BackOffExecution execution = backOff.start();
assertEquals(200L, execution.nextBackOff());
assertEquals(200L, execution.nextBackOff());
assertEquals(BackOffExecution.STOP, execution.nextBackOff());
assertThat(execution.nextBackOff()).isEqualTo(200L);
assertThat(execution.nextBackOff()).isEqualTo(200L);
assertThat(execution.nextBackOff()).isEqualTo(BackOffExecution.STOP);
}
@Test
@@ -59,34 +59,34 @@ public class FixedBackOffTests {
BackOffExecution execution = backOff.start();
BackOffExecution execution2 = backOff.start();
assertEquals(100L, execution.nextBackOff());
assertEquals(100L, execution2.nextBackOff());
assertEquals(BackOffExecution.STOP, execution.nextBackOff());
assertEquals(BackOffExecution.STOP, execution2.nextBackOff());
assertThat(execution.nextBackOff()).isEqualTo(100L);
assertThat(execution2.nextBackOff()).isEqualTo(100L);
assertThat(execution.nextBackOff()).isEqualTo(BackOffExecution.STOP);
assertThat(execution2.nextBackOff()).isEqualTo(BackOffExecution.STOP);
}
@Test
public void liveUpdate() {
FixedBackOff backOff = new FixedBackOff(100L, 1);
BackOffExecution execution = backOff.start();
assertEquals(100L, execution.nextBackOff());
assertThat(execution.nextBackOff()).isEqualTo(100L);
backOff.setInterval(200L);
backOff.setMaxAttempts(2);
assertEquals(200L, execution.nextBackOff());
assertEquals(BackOffExecution.STOP, execution.nextBackOff());
assertThat(execution.nextBackOff()).isEqualTo(200L);
assertThat(execution.nextBackOff()).isEqualTo(BackOffExecution.STOP);
}
@Test
public void toStringContent() {
FixedBackOff backOff = new FixedBackOff(200L, 10);
BackOffExecution execution = backOff.start();
assertEquals("FixedBackOff{interval=200, currentAttempts=0, maxAttempts=10}", execution.toString());
assertThat(execution.toString()).isEqualTo("FixedBackOff{interval=200, currentAttempts=0, maxAttempts=10}");
execution.nextBackOff();
assertEquals("FixedBackOff{interval=200, currentAttempts=1, maxAttempts=10}", execution.toString());
assertThat(execution.toString()).isEqualTo("FixedBackOff{interval=200, currentAttempts=1, maxAttempts=10}");
execution.nextBackOff();
assertEquals("FixedBackOff{interval=200, currentAttempts=2, maxAttempts=10}", execution.toString());
assertThat(execution.toString()).isEqualTo("FixedBackOff{interval=200, currentAttempts=2, maxAttempts=10}");
}
}

View File

@@ -19,8 +19,7 @@ package org.springframework.util;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Stephane Nicoll
@@ -66,11 +65,11 @@ public class InstanceFilterTests {
}
private <T> void match(InstanceFilter<T> filter, T candidate) {
assertTrue("filter '" + filter + "' should match " + candidate, filter.match(candidate));
assertThat(filter.match(candidate)).as("filter '" + filter + "' should match " + candidate).isTrue();
}
private <T> void doNotMatch(InstanceFilter<T> filter, T candidate) {
assertFalse("filter '" + filter + "' should not match " + candidate, filter.match(candidate));
assertThat(filter.match(candidate)).as("filter '" + filter + "' should not match " + candidate).isFalse();
}
}

View File

@@ -20,9 +20,7 @@ import java.util.Iterator;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link LinkedCaseInsensitiveMap}.
@@ -37,101 +35,101 @@ public class LinkedCaseInsensitiveMapTests {
@Test
public void putAndGet() {
assertNull(map.put("key", "value1"));
assertEquals("value1", map.put("key", "value2"));
assertEquals("value2", map.put("key", "value3"));
assertEquals(1, map.size());
assertEquals("value3", map.get("key"));
assertEquals("value3", map.get("KEY"));
assertEquals("value3", map.get("Key"));
assertTrue(map.containsKey("key"));
assertTrue(map.containsKey("KEY"));
assertTrue(map.containsKey("Key"));
assertTrue(map.keySet().contains("key"));
assertTrue(map.keySet().contains("KEY"));
assertTrue(map.keySet().contains("Key"));
assertThat(map.put("key", "value1")).isNull();
assertThat(map.put("key", "value2")).isEqualTo("value1");
assertThat(map.put("key", "value3")).isEqualTo("value2");
assertThat(map.size()).isEqualTo(1);
assertThat(map.get("key")).isEqualTo("value3");
assertThat(map.get("KEY")).isEqualTo("value3");
assertThat(map.get("Key")).isEqualTo("value3");
assertThat(map.containsKey("key")).isTrue();
assertThat(map.containsKey("KEY")).isTrue();
assertThat(map.containsKey("Key")).isTrue();
assertThat(map.keySet().contains("key")).isTrue();
assertThat(map.keySet().contains("KEY")).isTrue();
assertThat(map.keySet().contains("Key")).isTrue();
}
@Test
public void putWithOverlappingKeys() {
assertNull(map.put("key", "value1"));
assertEquals("value1", map.put("KEY", "value2"));
assertEquals("value2", map.put("Key", "value3"));
assertEquals(1, map.size());
assertEquals("value3", map.get("key"));
assertEquals("value3", map.get("KEY"));
assertEquals("value3", map.get("Key"));
assertTrue(map.containsKey("key"));
assertTrue(map.containsKey("KEY"));
assertTrue(map.containsKey("Key"));
assertTrue(map.keySet().contains("key"));
assertTrue(map.keySet().contains("KEY"));
assertTrue(map.keySet().contains("Key"));
assertThat(map.put("key", "value1")).isNull();
assertThat(map.put("KEY", "value2")).isEqualTo("value1");
assertThat(map.put("Key", "value3")).isEqualTo("value2");
assertThat(map.size()).isEqualTo(1);
assertThat(map.get("key")).isEqualTo("value3");
assertThat(map.get("KEY")).isEqualTo("value3");
assertThat(map.get("Key")).isEqualTo("value3");
assertThat(map.containsKey("key")).isTrue();
assertThat(map.containsKey("KEY")).isTrue();
assertThat(map.containsKey("Key")).isTrue();
assertThat(map.keySet().contains("key")).isTrue();
assertThat(map.keySet().contains("KEY")).isTrue();
assertThat(map.keySet().contains("Key")).isTrue();
}
@Test
public void getOrDefault() {
assertNull(map.put("key", "value1"));
assertEquals("value1", map.put("KEY", "value2"));
assertEquals("value2", map.put("Key", "value3"));
assertEquals("value3", map.getOrDefault("key", "N"));
assertEquals("value3", map.getOrDefault("KEY", "N"));
assertEquals("value3", map.getOrDefault("Key", "N"));
assertEquals("N", map.getOrDefault("keeeey", "N"));
assertEquals("N", map.getOrDefault(new Object(), "N"));
assertThat(map.put("key", "value1")).isNull();
assertThat(map.put("KEY", "value2")).isEqualTo("value1");
assertThat(map.put("Key", "value3")).isEqualTo("value2");
assertThat(map.getOrDefault("key", "N")).isEqualTo("value3");
assertThat(map.getOrDefault("KEY", "N")).isEqualTo("value3");
assertThat(map.getOrDefault("Key", "N")).isEqualTo("value3");
assertThat(map.getOrDefault("keeeey", "N")).isEqualTo("N");
assertThat(map.getOrDefault(new Object(), "N")).isEqualTo("N");
}
@Test
public void getOrDefaultWithNullValue() {
assertNull(map.put("key", null));
assertNull(map.put("KEY", null));
assertNull(map.put("Key", null));
assertNull(map.getOrDefault("key", "N"));
assertNull(map.getOrDefault("KEY", "N"));
assertNull(map.getOrDefault("Key", "N"));
assertEquals("N", map.getOrDefault("keeeey", "N"));
assertEquals("N", map.getOrDefault(new Object(), "N"));
assertThat(map.put("key", null)).isNull();
assertThat(map.put("KEY", null)).isNull();
assertThat(map.put("Key", null)).isNull();
assertThat(map.getOrDefault("key", "N")).isNull();
assertThat(map.getOrDefault("KEY", "N")).isNull();
assertThat(map.getOrDefault("Key", "N")).isNull();
assertThat(map.getOrDefault("keeeey", "N")).isEqualTo("N");
assertThat(map.getOrDefault(new Object(), "N")).isEqualTo("N");
}
@Test
public void computeIfAbsentWithExistingValue() {
assertNull(map.putIfAbsent("key", "value1"));
assertEquals("value1", map.putIfAbsent("KEY", "value2"));
assertEquals("value1", map.put("Key", "value3"));
assertEquals("value3", map.computeIfAbsent("key", key -> "value1"));
assertEquals("value3", map.computeIfAbsent("KEY", key -> "value2"));
assertEquals("value3", map.computeIfAbsent("Key", key -> "value3"));
assertThat(map.putIfAbsent("key", "value1")).isNull();
assertThat(map.putIfAbsent("KEY", "value2")).isEqualTo("value1");
assertThat(map.put("Key", "value3")).isEqualTo("value1");
assertThat(map.computeIfAbsent("key", key2 -> "value1")).isEqualTo("value3");
assertThat(map.computeIfAbsent("KEY", key1 -> "value2")).isEqualTo("value3");
assertThat(map.computeIfAbsent("Key", key -> "value3")).isEqualTo("value3");
}
@Test
public void computeIfAbsentWithComputedValue() {
assertEquals("value1", map.computeIfAbsent("key", key -> "value1"));
assertEquals("value1", map.computeIfAbsent("KEY", key -> "value2"));
assertEquals("value1", map.computeIfAbsent("Key", key -> "value3"));
assertThat(map.computeIfAbsent("key", key2 -> "value1")).isEqualTo("value1");
assertThat(map.computeIfAbsent("KEY", key1 -> "value2")).isEqualTo("value1");
assertThat(map.computeIfAbsent("Key", key -> "value3")).isEqualTo("value1");
}
@Test
public void mapClone() {
assertNull(map.put("key", "value1"));
assertThat(map.put("key", "value1")).isNull();
LinkedCaseInsensitiveMap<String> copy = map.clone();
assertEquals(map.getLocale(), copy.getLocale());
assertEquals("value1", map.get("key"));
assertEquals("value1", map.get("KEY"));
assertEquals("value1", map.get("Key"));
assertEquals("value1", copy.get("key"));
assertEquals("value1", copy.get("KEY"));
assertEquals("value1", copy.get("Key"));
assertThat(copy.getLocale()).isEqualTo(map.getLocale());
assertThat(map.get("key")).isEqualTo("value1");
assertThat(map.get("KEY")).isEqualTo("value1");
assertThat(map.get("Key")).isEqualTo("value1");
assertThat(copy.get("key")).isEqualTo("value1");
assertThat(copy.get("KEY")).isEqualTo("value1");
assertThat(copy.get("Key")).isEqualTo("value1");
copy.put("Key", "value2");
assertEquals(1, map.size());
assertEquals(1, copy.size());
assertEquals("value1", map.get("key"));
assertEquals("value1", map.get("KEY"));
assertEquals("value1", map.get("Key"));
assertEquals("value2", copy.get("key"));
assertEquals("value2", copy.get("KEY"));
assertEquals("value2", copy.get("Key"));
assertThat(map.size()).isEqualTo(1);
assertThat(copy.size()).isEqualTo(1);
assertThat(map.get("key")).isEqualTo("value1");
assertThat(map.get("KEY")).isEqualTo("value1");
assertThat(map.get("Key")).isEqualTo("value1");
assertThat(copy.get("key")).isEqualTo("value2");
assertThat(copy.get("KEY")).isEqualTo("value2");
assertThat(copy.get("Key")).isEqualTo("value2");
}
@@ -140,7 +138,7 @@ public class LinkedCaseInsensitiveMapTests {
map.put("key", "value");
map.keySet().clear();
map.computeIfAbsent("key", k -> "newvalue");
assertEquals("newvalue", map.get("key"));
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
@@ -148,70 +146,70 @@ public class LinkedCaseInsensitiveMapTests {
map.put("key", "value");
map.keySet().remove("key");
map.computeIfAbsent("key", k -> "newvalue");
assertEquals("newvalue", map.get("key"));
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
public void removeFromKeySetViaIterator() {
map.put("key", "value");
nextAndRemove(map.keySet().iterator());
assertEquals(0, map.size());
assertThat(map.size()).isEqualTo(0);
map.computeIfAbsent("key", k -> "newvalue");
assertEquals("newvalue", map.get("key"));
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
public void clearFromValues() {
map.put("key", "value");
map.values().clear();
assertEquals(0, map.size());
assertThat(map.size()).isEqualTo(0);
map.computeIfAbsent("key", k -> "newvalue");
assertEquals("newvalue", map.get("key"));
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
public void removeFromValues() {
map.put("key", "value");
map.values().remove("value");
assertEquals(0, map.size());
assertThat(map.size()).isEqualTo(0);
map.computeIfAbsent("key", k -> "newvalue");
assertEquals("newvalue", map.get("key"));
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
public void removeFromValuesViaIterator() {
map.put("key", "value");
nextAndRemove(map.values().iterator());
assertEquals(0, map.size());
assertThat(map.size()).isEqualTo(0);
map.computeIfAbsent("key", k -> "newvalue");
assertEquals("newvalue", map.get("key"));
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
public void clearFromEntrySet() {
map.put("key", "value");
map.entrySet().clear();
assertEquals(0, map.size());
assertThat(map.size()).isEqualTo(0);
map.computeIfAbsent("key", k -> "newvalue");
assertEquals("newvalue", map.get("key"));
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
public void removeFromEntrySet() {
map.put("key", "value");
map.entrySet().remove(map.entrySet().iterator().next());
assertEquals(0, map.size());
assertThat(map.size()).isEqualTo(0);
map.computeIfAbsent("key", k -> "newvalue");
assertEquals("newvalue", map.get("key"));
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
public void removeFromEntrySetViaIterator() {
map.put("key", "value");
nextAndRemove(map.entrySet().iterator());
assertEquals(0, map.size());
assertThat(map.size()).isEqualTo(0);
map.computeIfAbsent("key", k -> "newvalue");
assertEquals("newvalue", map.get("key"));
assertThat(map.get("key")).isEqualTo("newvalue");
}
private void nextAndRemove(Iterator<?> iterator) {

View File

@@ -25,8 +25,7 @@ import java.util.Map;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Arjen Poutsma
@@ -41,39 +40,39 @@ public class LinkedMultiValueMapTests {
public void add() {
map.add("key", "value1");
map.add("key", "value2");
assertEquals(1, map.size());
assertThat(map.size()).isEqualTo(1);
List<String> expected = new ArrayList<>(2);
expected.add("value1");
expected.add("value2");
assertEquals(expected, map.get("key"));
assertThat(map.get("key")).isEqualTo(expected);
}
@Test
public void set() {
map.set("key", "value1");
map.set("key", "value2");
assertEquals(1, map.size());
assertEquals(Collections.singletonList("value2"), map.get("key"));
assertThat(map.size()).isEqualTo(1);
assertThat(map.get("key")).isEqualTo(Collections.singletonList("value2"));
}
@Test
public void addAll() {
map.add("key", "value1");
map.addAll("key", Arrays.asList("value2", "value3"));
assertEquals(1, map.size());
assertThat(map.size()).isEqualTo(1);
List<String> expected = new ArrayList<>(2);
expected.add("value1");
expected.add("value2");
expected.add("value3");
assertEquals(expected, map.get("key"));
assertThat(map.get("key")).isEqualTo(expected);
}
@Test
public void addAllWithEmptyList() {
map.addAll("key", Collections.emptyList());
assertEquals(1, map.size());
assertEquals(Collections.emptyList(), map.get("key"));
assertNull(map.getFirst("key"));
assertThat(map.size()).isEqualTo(1);
assertThat(map.get("key")).isEqualTo(Collections.emptyList());
assertThat(map.getFirst("key")).isNull();
}
@Test
@@ -82,15 +81,15 @@ public class LinkedMultiValueMapTests {
values.add("value1");
values.add("value2");
map.put("key", values);
assertEquals("value1", map.getFirst("key"));
assertNull(map.getFirst("other"));
assertThat(map.getFirst("key")).isEqualTo("value1");
assertThat(map.getFirst("other")).isNull();
}
@Test
public void getFirstWithEmptyList() {
map.put("key", Collections.emptyList());
assertNull(map.getFirst("key"));
assertNull(map.getFirst("other"));
assertThat(map.getFirst("key")).isNull();
assertThat(map.getFirst("other")).isNull();
}
@Test
@@ -100,30 +99,30 @@ public class LinkedMultiValueMapTests {
values.add("value2");
map.put("key", values);
Map<String, String> svm = map.toSingleValueMap();
assertEquals(1, svm.size());
assertEquals("value1", svm.get("key"));
assertThat(svm.size()).isEqualTo(1);
assertThat(svm.get("key")).isEqualTo("value1");
}
@Test
public void toSingleValueMapWithEmptyList() {
map.put("key", Collections.emptyList());
Map<String, String> svm = map.toSingleValueMap();
assertEquals(0, svm.size());
assertNull(svm.get("key"));
assertThat(svm.size()).isEqualTo(0);
assertThat(svm.get("key")).isNull();
}
@Test
public void equals() {
map.set("key1", "value1");
assertEquals(map, map);
assertThat(map).isEqualTo(map);
MultiValueMap<String, String> o1 = new LinkedMultiValueMap<>();
o1.set("key1", "value1");
assertEquals(map, o1);
assertEquals(o1, map);
assertThat(o1).isEqualTo(map);
assertThat(map).isEqualTo(o1);
Map<String, List<String>> o2 = new HashMap<>();
o2.put("key1", Collections.singletonList("value1"));
assertEquals(map, o2);
assertEquals(o2, map);
assertThat(o2).isEqualTo(map);
assertThat(map).isEqualTo(o2);
}
}

View File

@@ -22,8 +22,8 @@ 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.junit.Assert.assertEquals;
/**
* @author Colin Sampaleanu
@@ -42,7 +42,7 @@ public class MethodInvokerTests {
mi.setTargetMethod("method1");
mi.prepare();
Integer i = (Integer) mi.invoke();
assertEquals(1, i.intValue());
assertThat(i.intValue()).isEqualTo(1);
// defensive check: singleton, non-static should work with null array
tc1 = new TestClass1();
@@ -52,7 +52,7 @@ public class MethodInvokerTests {
mi.setArguments((Object[]) null);
mi.prepare();
i = (Integer) mi.invoke();
assertEquals(1, i.intValue());
assertThat(i.intValue()).isEqualTo(1);
// sanity check: check that argument count matching works
mi = new MethodInvoker();
@@ -60,14 +60,14 @@ public class MethodInvokerTests {
mi.setTargetMethod("supertypes");
mi.setArguments(new ArrayList<>(), new ArrayList<>(), "hello");
mi.prepare();
assertEquals("hello", mi.invoke());
assertThat(mi.invoke()).isEqualTo("hello");
mi = new MethodInvoker();
mi.setTargetClass(TestClass1.class);
mi.setTargetMethod("supertypes2");
mi.setArguments(new ArrayList<>(), new ArrayList<>(), "hello", "bogus");
mi.prepare();
assertEquals("hello", mi.invoke());
assertThat(mi.invoke()).isEqualTo("hello");
// Sanity check: check that argument conversion doesn't work with plain MethodInvoker
mi = new MethodInvoker();
@@ -98,7 +98,7 @@ public class MethodInvokerTests {
methodInvoker.setArguments(new Purchaser());
methodInvoker.prepare();
String greeting = (String) methodInvoker.invoke();
assertEquals("purchaser: hello", greeting);
assertThat(greeting).isEqualTo("purchaser: hello");
}
@Test
@@ -109,7 +109,7 @@ public class MethodInvokerTests {
methodInvoker.setArguments(new Shopper());
methodInvoker.prepare();
String greeting = (String) methodInvoker.invoke();
assertEquals("purchaser: may I help you?", greeting);
assertThat(greeting).isEqualTo("purchaser: may I help you?");
}
@Test
@@ -120,7 +120,7 @@ public class MethodInvokerTests {
methodInvoker.setArguments(new Salesman());
methodInvoker.prepare();
String greeting = (String) methodInvoker.invoke();
assertEquals("greetable: how are sales?", greeting);
assertThat(greeting).isEqualTo("greetable: how are sales?");
}
@Test
@@ -131,7 +131,7 @@ public class MethodInvokerTests {
methodInvoker.setArguments(new Customer());
methodInvoker.prepare();
String greeting = (String) methodInvoker.invoke();
assertEquals("customer: good day", greeting);
assertThat(greeting).isEqualTo("customer: good day");
}
@Test
@@ -142,7 +142,7 @@ public class MethodInvokerTests {
methodInvoker.setArguments(new Regular("Kotter"));
methodInvoker.prepare();
String greeting = (String) methodInvoker.invoke();
assertEquals("regular: welcome back Kotter", greeting);
assertThat(greeting).isEqualTo("regular: welcome back Kotter");
}
@Test
@@ -153,7 +153,7 @@ public class MethodInvokerTests {
methodInvoker.setArguments(new VIP("Fonzie"));
methodInvoker.prepare();
String greeting = (String) methodInvoker.invoke();
assertEquals("regular: whassup dude?", greeting);
assertThat(greeting).isEqualTo("regular: whassup dude?");
}

View File

@@ -28,13 +28,9 @@ import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for {@link MimeType}.
@@ -86,111 +82,111 @@ public class MimeTypeTests {
public void parseCharset() {
String s = "text/html; charset=iso-8859-1";
MimeType mimeType = MimeType.valueOf(s);
assertEquals("Invalid type", "text", mimeType.getType());
assertEquals("Invalid subtype", "html", mimeType.getSubtype());
assertEquals("Invalid charset", StandardCharsets.ISO_8859_1, mimeType.getCharset());
assertThat(mimeType.getType()).as("Invalid type").isEqualTo("text");
assertThat(mimeType.getSubtype()).as("Invalid subtype").isEqualTo("html");
assertThat(mimeType.getCharset()).as("Invalid charset").isEqualTo(StandardCharsets.ISO_8859_1);
}
@Test
public void parseQuotedCharset() {
String s = "application/xml;charset=\"utf-8\"";
MimeType mimeType = MimeType.valueOf(s);
assertEquals("Invalid type", "application", mimeType.getType());
assertEquals("Invalid subtype", "xml", mimeType.getSubtype());
assertEquals("Invalid charset", StandardCharsets.UTF_8, mimeType.getCharset());
assertThat(mimeType.getType()).as("Invalid type").isEqualTo("application");
assertThat(mimeType.getSubtype()).as("Invalid subtype").isEqualTo("xml");
assertThat(mimeType.getCharset()).as("Invalid charset").isEqualTo(StandardCharsets.UTF_8);
}
@Test
public void parseQuotedSeparator() {
String s = "application/xop+xml;charset=utf-8;type=\"application/soap+xml;action=\\\"https://x.y.z\\\"\"";
MimeType mimeType = MimeType.valueOf(s);
assertEquals("Invalid type", "application", mimeType.getType());
assertEquals("Invalid subtype", "xop+xml", mimeType.getSubtype());
assertEquals("Invalid charset", StandardCharsets.UTF_8, mimeType.getCharset());
assertEquals("\"application/soap+xml;action=\\\"https://x.y.z\\\"\"", mimeType.getParameter("type"));
assertThat(mimeType.getType()).as("Invalid type").isEqualTo("application");
assertThat(mimeType.getSubtype()).as("Invalid subtype").isEqualTo("xop+xml");
assertThat(mimeType.getCharset()).as("Invalid charset").isEqualTo(StandardCharsets.UTF_8);
assertThat(mimeType.getParameter("type")).isEqualTo("\"application/soap+xml;action=\\\"https://x.y.z\\\"\"");
}
@Test
public void withConversionService() {
ConversionService conversionService = new DefaultConversionService();
assertTrue(conversionService.canConvert(String.class, MimeType.class));
assertThat(conversionService.canConvert(String.class, MimeType.class)).isTrue();
MimeType mimeType = MimeType.valueOf("application/xml");
assertEquals(mimeType, conversionService.convert("application/xml", MimeType.class));
assertThat(conversionService.convert("application/xml", MimeType.class)).isEqualTo(mimeType);
}
@Test
public void includes() {
MimeType textPlain = MimeTypeUtils.TEXT_PLAIN;
assertTrue("Equal types is not inclusive", textPlain.includes(textPlain));
assertThat(textPlain.includes(textPlain)).as("Equal types is not inclusive").isTrue();
MimeType allText = new MimeType("text");
assertTrue("All subtypes is not inclusive", allText.includes(textPlain));
assertFalse("All subtypes is inclusive", textPlain.includes(allText));
assertThat(allText.includes(textPlain)).as("All subtypes is not inclusive").isTrue();
assertThat(textPlain.includes(allText)).as("All subtypes is inclusive").isFalse();
assertTrue("All types is not inclusive", MimeTypeUtils.ALL.includes(textPlain));
assertFalse("All types is inclusive", textPlain.includes(MimeTypeUtils.ALL));
assertThat(MimeTypeUtils.ALL.includes(textPlain)).as("All types is not inclusive").isTrue();
assertThat(textPlain.includes(MimeTypeUtils.ALL)).as("All types is inclusive").isFalse();
assertTrue("All types is not inclusive", MimeTypeUtils.ALL.includes(textPlain));
assertFalse("All types is inclusive", textPlain.includes(MimeTypeUtils.ALL));
assertThat(MimeTypeUtils.ALL.includes(textPlain)).as("All types is not inclusive").isTrue();
assertThat(textPlain.includes(MimeTypeUtils.ALL)).as("All types is inclusive").isFalse();
MimeType applicationSoapXml = new MimeType("application", "soap+xml");
MimeType applicationWildcardXml = new MimeType("application", "*+xml");
MimeType suffixXml = new MimeType("application", "x.y+z+xml"); // SPR-15795
assertTrue(applicationSoapXml.includes(applicationSoapXml));
assertTrue(applicationWildcardXml.includes(applicationWildcardXml));
assertTrue(applicationWildcardXml.includes(suffixXml));
assertThat(applicationSoapXml.includes(applicationSoapXml)).isTrue();
assertThat(applicationWildcardXml.includes(applicationWildcardXml)).isTrue();
assertThat(applicationWildcardXml.includes(suffixXml)).isTrue();
assertTrue(applicationWildcardXml.includes(applicationSoapXml));
assertFalse(applicationSoapXml.includes(applicationWildcardXml));
assertFalse(suffixXml.includes(applicationWildcardXml));
assertThat(applicationWildcardXml.includes(applicationSoapXml)).isTrue();
assertThat(applicationSoapXml.includes(applicationWildcardXml)).isFalse();
assertThat(suffixXml.includes(applicationWildcardXml)).isFalse();
assertFalse(applicationWildcardXml.includes(MimeTypeUtils.APPLICATION_JSON));
assertThat(applicationWildcardXml.includes(MimeTypeUtils.APPLICATION_JSON)).isFalse();
}
@Test
public void isCompatible() {
MimeType textPlain = MimeTypeUtils.TEXT_PLAIN;
assertTrue("Equal types is not compatible", textPlain.isCompatibleWith(textPlain));
assertThat(textPlain.isCompatibleWith(textPlain)).as("Equal types is not compatible").isTrue();
MimeType allText = new MimeType("text");
assertTrue("All subtypes is not compatible", allText.isCompatibleWith(textPlain));
assertTrue("All subtypes is not compatible", textPlain.isCompatibleWith(allText));
assertThat(allText.isCompatibleWith(textPlain)).as("All subtypes is not compatible").isTrue();
assertThat(textPlain.isCompatibleWith(allText)).as("All subtypes is not compatible").isTrue();
assertTrue("All types is not compatible", MimeTypeUtils.ALL.isCompatibleWith(textPlain));
assertTrue("All types is not compatible", textPlain.isCompatibleWith(MimeTypeUtils.ALL));
assertThat(MimeTypeUtils.ALL.isCompatibleWith(textPlain)).as("All types is not compatible").isTrue();
assertThat(textPlain.isCompatibleWith(MimeTypeUtils.ALL)).as("All types is not compatible").isTrue();
assertTrue("All types is not compatible", MimeTypeUtils.ALL.isCompatibleWith(textPlain));
assertTrue("All types is compatible", textPlain.isCompatibleWith(MimeTypeUtils.ALL));
assertThat(MimeTypeUtils.ALL.isCompatibleWith(textPlain)).as("All types is not compatible").isTrue();
assertThat(textPlain.isCompatibleWith(MimeTypeUtils.ALL)).as("All types is compatible").isTrue();
MimeType applicationSoapXml = new MimeType("application", "soap+xml");
MimeType applicationWildcardXml = new MimeType("application", "*+xml");
MimeType suffixXml = new MimeType("application", "x.y+z+xml"); // SPR-15795
assertTrue(applicationSoapXml.isCompatibleWith(applicationSoapXml));
assertTrue(applicationWildcardXml.isCompatibleWith(applicationWildcardXml));
assertTrue(applicationWildcardXml.isCompatibleWith(suffixXml));
assertThat(applicationSoapXml.isCompatibleWith(applicationSoapXml)).isTrue();
assertThat(applicationWildcardXml.isCompatibleWith(applicationWildcardXml)).isTrue();
assertThat(applicationWildcardXml.isCompatibleWith(suffixXml)).isTrue();
assertTrue(applicationWildcardXml.isCompatibleWith(applicationSoapXml));
assertTrue(applicationSoapXml.isCompatibleWith(applicationWildcardXml));
assertTrue(suffixXml.isCompatibleWith(applicationWildcardXml));
assertThat(applicationWildcardXml.isCompatibleWith(applicationSoapXml)).isTrue();
assertThat(applicationSoapXml.isCompatibleWith(applicationWildcardXml)).isTrue();
assertThat(suffixXml.isCompatibleWith(applicationWildcardXml)).isTrue();
assertFalse(applicationWildcardXml.isCompatibleWith(MimeTypeUtils.APPLICATION_JSON));
assertThat(applicationWildcardXml.isCompatibleWith(MimeTypeUtils.APPLICATION_JSON)).isFalse();
}
@Test
public void testToString() {
MimeType mimeType = new MimeType("text", "plain");
String result = mimeType.toString();
assertEquals("Invalid toString() returned", "text/plain", result);
assertThat(result).as("Invalid toString() returned").isEqualTo("text/plain");
}
@Test
public void parseMimeType() {
String s = "audio/*";
MimeType mimeType = MimeTypeUtils.parseMimeType(s);
assertEquals("Invalid type", "audio", mimeType.getType());
assertEquals("Invalid subtype", "*", mimeType.getSubtype());
assertThat(mimeType.getType()).as("Invalid type").isEqualTo("audio");
assertThat(mimeType.getSubtype()).as("Invalid subtype").isEqualTo("*");
}
@Test
@@ -262,25 +258,25 @@ public class MimeTypeTests {
@Test // SPR-8917
public void parseMimeTypeQuotedParameterValue() {
MimeType mimeType = MimeTypeUtils.parseMimeType("audio/*;attr=\"v>alue\"");
assertEquals("\"v>alue\"", mimeType.getParameter("attr"));
assertThat(mimeType.getParameter("attr")).isEqualTo("\"v>alue\"");
}
@Test // SPR-8917
public void parseMimeTypeSingleQuotedParameterValue() {
MimeType mimeType = MimeTypeUtils.parseMimeType("audio/*;attr='v>alue'");
assertEquals("'v>alue'", mimeType.getParameter("attr"));
assertThat(mimeType.getParameter("attr")).isEqualTo("'v>alue'");
}
@Test // SPR-16630
public void parseMimeTypeWithSpacesAroundEquals() {
MimeType mimeType = MimeTypeUtils.parseMimeType("multipart/x-mixed-replace;boundary = --myboundary");
assertEquals("--myboundary", mimeType.getParameter("boundary"));
assertThat(mimeType.getParameter("boundary")).isEqualTo("--myboundary");
}
@Test // SPR-16630
public void parseMimeTypeWithSpacesAroundEqualsAndQuotedValue() {
MimeType mimeType = MimeTypeUtils.parseMimeType("text/plain; foo = \" bar \" ");
assertEquals("\" bar \"", mimeType.getParameter("foo"));
assertThat(mimeType.getParameter("foo")).isEqualTo("\" bar \"");
}
@Test
@@ -293,12 +289,12 @@ public class MimeTypeTests {
public void parseMimeTypes() {
String s = "text/plain, text/html, text/x-dvi, text/x-c";
List<MimeType> mimeTypes = MimeTypeUtils.parseMimeTypes(s);
assertNotNull("No mime types returned", mimeTypes);
assertEquals("Invalid amount of mime types", 4, mimeTypes.size());
assertThat(mimeTypes).as("No mime types returned").isNotNull();
assertThat(mimeTypes.size()).as("Invalid amount of mime types").isEqualTo(4);
mimeTypes = MimeTypeUtils.parseMimeTypes(null);
assertNotNull("No mime types returned", mimeTypes);
assertEquals("Invalid amount of mime types", 0, mimeTypes.size());
assertThat(mimeTypes).as("No mime types returned").isNotNull();
assertThat(mimeTypes.size()).as("Invalid amount of mime types").isEqualTo(0);
}
@Test // SPR-17459
@@ -314,9 +310,9 @@ public class MimeTypeTests {
private void testWithQuotedParameters(String... mimeTypes) {
String s = String.join(",", mimeTypes);
List<MimeType> actual = MimeTypeUtils.parseMimeTypes(s);
assertEquals(mimeTypes.length, actual.size());
assertThat(actual.size()).isEqualTo(mimeTypes.length);
for (int i=0; i < mimeTypes.length; i++) {
assertEquals(mimeTypes[i], actual.get(i).toString());
assertThat(actual.get(i).toString()).isEqualTo(mimeTypes[i]);
}
}
@@ -328,11 +324,11 @@ public class MimeTypeTests {
MimeType audioBasicLevel = new MimeType("audio", "basic", singletonMap("level", "1"));
// equal
assertEquals("Invalid comparison result", 0, audioBasic.compareTo(audioBasic));
assertEquals("Invalid comparison result", 0, audio.compareTo(audio));
assertEquals("Invalid comparison result", 0, audioBasicLevel.compareTo(audioBasicLevel));
assertThat(audioBasic.compareTo(audioBasic)).as("Invalid comparison result").isEqualTo(0);
assertThat(audio.compareTo(audio)).as("Invalid comparison result").isEqualTo(0);
assertThat(audioBasicLevel.compareTo(audioBasicLevel)).as("Invalid comparison result").isEqualTo(0);
assertTrue("Invalid comparison result", audioBasicLevel.compareTo(audio) > 0);
assertThat(audioBasicLevel.compareTo(audio) > 0).as("Invalid comparison result").isTrue();
List<MimeType> expected = new ArrayList<>();
expected.add(audio);
@@ -348,7 +344,7 @@ public class MimeTypeTests {
Collections.sort(result);
for (int j = 0; j < result.size(); j++) {
assertSame("Invalid media type at " + j + ", run " + i, expected.get(j), result.get(j));
assertThat(result.get(j)).as("Invalid media type at " + j + ", run " + i).isSameAs(expected.get(j));
}
}
}
@@ -357,18 +353,18 @@ public class MimeTypeTests {
public void compareToCaseSensitivity() {
MimeType m1 = new MimeType("audio", "basic");
MimeType m2 = new MimeType("Audio", "Basic");
assertEquals("Invalid comparison result", 0, m1.compareTo(m2));
assertEquals("Invalid comparison result", 0, m2.compareTo(m1));
assertThat(m1.compareTo(m2)).as("Invalid comparison result").isEqualTo(0);
assertThat(m2.compareTo(m1)).as("Invalid comparison result").isEqualTo(0);
m1 = new MimeType("audio", "basic", singletonMap("foo", "bar"));
m2 = new MimeType("audio", "basic", singletonMap("Foo", "bar"));
assertEquals("Invalid comparison result", 0, m1.compareTo(m2));
assertEquals("Invalid comparison result", 0, m2.compareTo(m1));
assertThat(m1.compareTo(m2)).as("Invalid comparison result").isEqualTo(0);
assertThat(m2.compareTo(m1)).as("Invalid comparison result").isEqualTo(0);
m1 = new MimeType("audio", "basic", singletonMap("foo", "bar"));
m2 = new MimeType("audio", "basic", singletonMap("foo", "Bar"));
assertTrue("Invalid comparison result", m1.compareTo(m2) != 0);
assertTrue("Invalid comparison result", m2.compareTo(m1) != 0);
assertThat(m1.compareTo(m2) != 0).as("Invalid comparison result").isTrue();
assertThat(m2.compareTo(m1) != 0).as("Invalid comparison result").isTrue();
}
/**
@@ -379,10 +375,10 @@ public class MimeTypeTests {
public void equalsIsCaseInsensitiveForCharsets() {
MimeType m1 = new MimeType("text", "plain", singletonMap("charset", "UTF-8"));
MimeType m2 = new MimeType("text", "plain", singletonMap("charset", "utf-8"));
assertEquals(m1, m2);
assertEquals(m2, m1);
assertEquals(0, m1.compareTo(m2));
assertEquals(0, m2.compareTo(m1));
assertThat(m2).isEqualTo(m1);
assertThat(m1).isEqualTo(m2);
assertThat(m1.compareTo(m2)).isEqualTo(0);
assertThat(m2.compareTo(m1)).isEqualTo(0);
}
}

View File

@@ -23,8 +23,8 @@ import java.util.Locale;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
/**
* @author Rob Harrop
@@ -41,12 +41,12 @@ public class NumberUtilsTests {
String aFloat = "" + Float.MAX_VALUE;
String aDouble = "" + Double.MAX_VALUE;
assertEquals("Byte did not parse", Byte.valueOf(Byte.MAX_VALUE), NumberUtils.parseNumber(aByte, Byte.class));
assertEquals("Short did not parse", Short.valueOf(Short.MAX_VALUE), NumberUtils.parseNumber(aShort, Short.class));
assertEquals("Integer did not parse", Integer.valueOf(Integer.MAX_VALUE), NumberUtils.parseNumber(anInteger, Integer.class));
assertEquals("Long did not parse", Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class));
assertEquals("Float did not parse", Float.valueOf(Float.MAX_VALUE), NumberUtils.parseNumber(aFloat, Float.class));
assertEquals("Double did not parse", Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class));
assertThat(NumberUtils.parseNumber(aByte, Byte.class)).as("Byte did not parse").isEqualTo(Byte.valueOf(Byte.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aShort, Short.class)).as("Short did not parse").isEqualTo(Short.valueOf(Short.MAX_VALUE));
assertThat(NumberUtils.parseNumber(anInteger, Integer.class)).as("Integer did not parse").isEqualTo(Integer.valueOf(Integer.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aLong, Long.class)).as("Long did not parse").isEqualTo(Long.valueOf(Long.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aFloat, Float.class)).as("Float did not parse").isEqualTo(Float.valueOf(Float.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aDouble, Double.class)).as("Double did not parse").isEqualTo(Double.valueOf(Double.MAX_VALUE));
}
@Test
@@ -59,12 +59,12 @@ public class NumberUtilsTests {
String aFloat = "" + Float.MAX_VALUE;
String aDouble = "" + Double.MAX_VALUE;
assertEquals("Byte did not parse", Byte.valueOf(Byte.MAX_VALUE), NumberUtils.parseNumber(aByte, Byte.class, nf));
assertEquals("Short did not parse", Short.valueOf(Short.MAX_VALUE), NumberUtils.parseNumber(aShort, Short.class, nf));
assertEquals("Integer did not parse", Integer.valueOf(Integer.MAX_VALUE), NumberUtils.parseNumber(anInteger, Integer.class, nf));
assertEquals("Long did not parse", Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf));
assertEquals("Float did not parse", Float.valueOf(Float.MAX_VALUE), NumberUtils.parseNumber(aFloat, Float.class, nf));
assertEquals("Double did not parse", Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf));
assertThat(NumberUtils.parseNumber(aByte, Byte.class, nf)).as("Byte did not parse").isEqualTo(Byte.valueOf(Byte.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aShort, Short.class, nf)).as("Short did not parse").isEqualTo(Short.valueOf(Short.MAX_VALUE));
assertThat(NumberUtils.parseNumber(anInteger, Integer.class, nf)).as("Integer did not parse").isEqualTo(Integer.valueOf(Integer.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aLong, Long.class, nf)).as("Long did not parse").isEqualTo(Long.valueOf(Long.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aFloat, Float.class, nf)).as("Float did not parse").isEqualTo(Float.valueOf(Float.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aDouble, Double.class, nf)).as("Double did not parse").isEqualTo(Double.valueOf(Double.MAX_VALUE));
}
@Test
@@ -76,12 +76,12 @@ public class NumberUtilsTests {
String aFloat = " " + Float.MAX_VALUE + " ";
String aDouble = " " + Double.MAX_VALUE + " ";
assertEquals("Byte did not parse", Byte.valueOf(Byte.MAX_VALUE), NumberUtils.parseNumber(aByte, Byte.class));
assertEquals("Short did not parse", Short.valueOf(Short.MAX_VALUE), NumberUtils.parseNumber(aShort, Short.class));
assertEquals("Integer did not parse", Integer.valueOf(Integer.MAX_VALUE), NumberUtils.parseNumber(anInteger, Integer.class));
assertEquals("Long did not parse", Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class));
assertEquals("Float did not parse", Float.valueOf(Float.MAX_VALUE), NumberUtils.parseNumber(aFloat, Float.class));
assertEquals("Double did not parse", Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class));
assertThat(NumberUtils.parseNumber(aByte, Byte.class)).as("Byte did not parse").isEqualTo(Byte.valueOf(Byte.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aShort, Short.class)).as("Short did not parse").isEqualTo(Short.valueOf(Short.MAX_VALUE));
assertThat(NumberUtils.parseNumber(anInteger, Integer.class)).as("Integer did not parse").isEqualTo(Integer.valueOf(Integer.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aLong, Long.class)).as("Long did not parse").isEqualTo(Long.valueOf(Long.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aFloat, Float.class)).as("Float did not parse").isEqualTo(Float.valueOf(Float.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aDouble, Double.class)).as("Double did not parse").isEqualTo(Double.valueOf(Double.MAX_VALUE));
}
@Test
@@ -94,12 +94,12 @@ public class NumberUtilsTests {
String aFloat = " " + Float.MAX_VALUE + " ";
String aDouble = " " + Double.MAX_VALUE + " ";
assertEquals("Byte did not parse", Byte.valueOf(Byte.MAX_VALUE), NumberUtils.parseNumber(aByte, Byte.class, nf));
assertEquals("Short did not parse", Short.valueOf(Short.MAX_VALUE), NumberUtils.parseNumber(aShort, Short.class, nf));
assertEquals("Integer did not parse", Integer.valueOf(Integer.MAX_VALUE), NumberUtils.parseNumber(anInteger, Integer.class, nf));
assertEquals("Long did not parse", Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf));
assertEquals("Float did not parse", Float.valueOf(Float.MAX_VALUE), NumberUtils.parseNumber(aFloat, Float.class, nf));
assertEquals("Double did not parse", Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf));
assertThat(NumberUtils.parseNumber(aByte, Byte.class, nf)).as("Byte did not parse").isEqualTo(Byte.valueOf(Byte.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aShort, Short.class, nf)).as("Short did not parse").isEqualTo(Short.valueOf(Short.MAX_VALUE));
assertThat(NumberUtils.parseNumber(anInteger, Integer.class, nf)).as("Integer did not parse").isEqualTo(Integer.valueOf(Integer.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aLong, Long.class, nf)).as("Long did not parse").isEqualTo(Long.valueOf(Long.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aFloat, Float.class, nf)).as("Float did not parse").isEqualTo(Float.valueOf(Float.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aDouble, Double.class, nf)).as("Double did not parse").isEqualTo(Double.valueOf(Double.MAX_VALUE));
}
@Test
@@ -114,8 +114,7 @@ public class NumberUtilsTests {
assertShortEquals(aShort);
assertIntegerEquals(anInteger);
assertLongEquals(aLong);
assertEquals("BigInteger did not parse",
new BigInteger(aReallyBigInt, 16), NumberUtils.parseNumber("0x" + aReallyBigInt, BigInteger.class));
assertThat(NumberUtils.parseNumber("0x" + aReallyBigInt, BigInteger.class)).as("BigInteger did not parse").isEqualTo(new BigInteger(aReallyBigInt, 16));
}
@Test
@@ -130,48 +129,47 @@ public class NumberUtilsTests {
assertNegativeShortEquals(aShort);
assertNegativeIntegerEquals(anInteger);
assertNegativeLongEquals(aLong);
assertEquals("BigInteger did not parse",
new BigInteger(aReallyBigInt, 16).negate(), NumberUtils.parseNumber("-0x" + aReallyBigInt, BigInteger.class));
assertThat(NumberUtils.parseNumber("-0x" + aReallyBigInt, BigInteger.class)).as("BigInteger did not parse").isEqualTo(new BigInteger(aReallyBigInt, 16).negate());
}
@Test
public void convertDoubleToBigInteger() {
Double decimal = Double.valueOf(3.14d);
assertEquals(new BigInteger("3"), NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class));
assertThat(NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class)).isEqualTo(new BigInteger("3"));
}
@Test
public void convertBigDecimalToBigInteger() {
String number = "987459837583750387355346";
BigDecimal decimal = new BigDecimal(number);
assertEquals(new BigInteger(number), NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class));
assertThat(NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class)).isEqualTo(new BigInteger(number));
}
@Test
public void convertNonExactBigDecimalToBigInteger() {
BigDecimal decimal = new BigDecimal("987459837583750387355346.14");
assertEquals(new BigInteger("987459837583750387355346"), NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class));
assertThat(NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class)).isEqualTo(new BigInteger("987459837583750387355346"));
}
@Test
public void parseBigDecimalNumber1() {
String bigDecimalAsString = "0.10";
Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class);
assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal);
assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString));
}
@Test
public void parseBigDecimalNumber2() {
String bigDecimalAsString = "0.001";
Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class);
assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal);
assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString));
}
@Test
public void parseBigDecimalNumber3() {
String bigDecimalAsString = "3.14159265358979323846";
Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class);
assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal);
assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString));
}
@Test
@@ -179,7 +177,7 @@ public class NumberUtilsTests {
String bigDecimalAsString = "0.10";
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH);
Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class, numberFormat);
assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal);
assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString));
}
@Test
@@ -187,7 +185,7 @@ public class NumberUtilsTests {
String bigDecimalAsString = "0.001";
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH);
Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class, numberFormat);
assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal);
assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString));
}
@Test
@@ -195,7 +193,7 @@ public class NumberUtilsTests {
String bigDecimalAsString = "3.14159265358979323846";
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH);
Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class, numberFormat);
assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal);
assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString));
}
@Test
@@ -212,8 +210,8 @@ public class NumberUtilsTests {
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Integer.class));
assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class));
assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class));
assertThat(NumberUtils.parseNumber(aLong, Long.class)).isEqualTo(Long.valueOf(Long.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aDouble, Double.class)).isEqualTo(Double.valueOf(Double.MAX_VALUE));
}
@Test
@@ -230,8 +228,8 @@ public class NumberUtilsTests {
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Integer.class));
assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.parseNumber(aLong, Long.class));
assertEquals(Double.valueOf(Double.MIN_VALUE), NumberUtils.parseNumber(aDouble, Double.class));
assertThat(NumberUtils.parseNumber(aLong, Long.class)).isEqualTo(Long.valueOf(Long.MIN_VALUE));
assertThat(NumberUtils.parseNumber(aDouble, Double.class)).isEqualTo(Double.valueOf(Double.MIN_VALUE));
}
@Test
@@ -249,8 +247,8 @@ public class NumberUtilsTests {
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Integer.class, nf));
assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf));
assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf));
assertThat(NumberUtils.parseNumber(aLong, Long.class, nf)).isEqualTo(Long.valueOf(Long.MAX_VALUE));
assertThat(NumberUtils.parseNumber(aDouble, Double.class, nf)).isEqualTo(Double.valueOf(Double.MAX_VALUE));
}
@Test
@@ -268,51 +266,51 @@ public class NumberUtilsTests {
assertThatIllegalArgumentException().isThrownBy(() ->
NumberUtils.parseNumber(aLong, Integer.class, nf));
assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf));
assertEquals(Double.valueOf(Double.MIN_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf));
assertThat(NumberUtils.parseNumber(aLong, Long.class, nf)).isEqualTo(Long.valueOf(Long.MIN_VALUE));
assertThat(NumberUtils.parseNumber(aDouble, Double.class, nf)).isEqualTo(Double.valueOf(Double.MIN_VALUE));
}
@Test
public void convertToInteger() {
assertEquals(Integer.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(-1), Integer.class));
assertEquals(Integer.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(0), Integer.class));
assertEquals(Integer.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(1), Integer.class));
assertEquals(Integer.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MAX_VALUE), Integer.class));
assertEquals(Integer.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MAX_VALUE + 1), Integer.class));
assertEquals(Integer.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MIN_VALUE), Integer.class));
assertEquals(Integer.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MIN_VALUE - 1), Integer.class));
assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(-1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(-1)));
assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(0), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(0)));
assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(1)));
assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MAX_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MAX_VALUE + 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MIN_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MIN_VALUE - 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE));
assertEquals(Integer.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Long.valueOf(-1), Integer.class));
assertEquals(Integer.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(Long.valueOf(0), Integer.class));
assertEquals(Integer.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(Long.valueOf(1), Integer.class));
assertEquals(Integer.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MAX_VALUE), Integer.class));
assertEquals(Integer.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MAX_VALUE + 1), Integer.class));
assertEquals(Integer.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MIN_VALUE), Integer.class));
assertEquals(Integer.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MIN_VALUE - 1), Integer.class));
assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(-1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(-1)));
assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(0), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(0)));
assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(1)));
assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MAX_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MAX_VALUE + 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MIN_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MIN_VALUE - 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE));
assertEquals(Integer.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Integer.valueOf(-1), Integer.class));
assertEquals(Integer.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(Integer.valueOf(0), Integer.class));
assertEquals(Integer.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(Integer.valueOf(1), Integer.class));
assertEquals(Integer.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE), Integer.class));
assertEquals(Integer.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE + 1), Integer.class));
assertEquals(Integer.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE), Integer.class));
assertEquals(Integer.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE - 1), Integer.class));
assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(-1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(-1)));
assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(0), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(0)));
assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(1)));
assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE + 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE - 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE));
assertEquals(Integer.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) -1), Integer.class));
assertEquals(Integer.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 0), Integer.class));
assertEquals(Integer.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 1), Integer.class));
assertEquals(Integer.valueOf(Short.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MAX_VALUE), Integer.class));
assertEquals(Integer.valueOf(Short.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MAX_VALUE + 1)), Integer.class));
assertEquals(Integer.valueOf(Short.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MIN_VALUE), Integer.class));
assertEquals(Integer.valueOf(Short.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MIN_VALUE - 1)), Integer.class));
assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) -1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(-1)));
assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 0), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(0)));
assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(1)));
assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MAX_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Short.MAX_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MAX_VALUE + 1)), Integer.class)).isEqualTo(Integer.valueOf(Short.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MIN_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Short.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MIN_VALUE - 1)), Integer.class)).isEqualTo(Integer.valueOf(Short.MAX_VALUE));
assertEquals(Integer.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) -1), Integer.class));
assertEquals(Integer.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 0), Integer.class));
assertEquals(Integer.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 1), Integer.class));
assertEquals(Integer.valueOf(Byte.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MAX_VALUE), Integer.class));
assertEquals(Integer.valueOf(Byte.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MAX_VALUE + 1)), Integer.class));
assertEquals(Integer.valueOf(Byte.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MIN_VALUE), Integer.class));
assertEquals(Integer.valueOf(Byte.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MIN_VALUE - 1)), Integer.class));
assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) -1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(-1)));
assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 0), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(0)));
assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(1)));
assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MAX_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Byte.MAX_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MAX_VALUE + 1)), Integer.class)).isEqualTo(Integer.valueOf(Byte.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MIN_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Byte.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MIN_VALUE - 1)), Integer.class)).isEqualTo(Integer.valueOf(Byte.MAX_VALUE));
assertToNumberOverflow(Long.valueOf(Long.MAX_VALUE + 1), Integer.class);
assertToNumberOverflow(Long.valueOf(Long.MIN_VALUE - 1), Integer.class);
@@ -323,45 +321,45 @@ public class NumberUtilsTests {
@Test
public void convertToLong() {
assertEquals(Long.valueOf(Long.valueOf(-1)), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(-1), Long.class));
assertEquals(Long.valueOf(Long.valueOf(0)), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(0), Long.class));
assertEquals(Long.valueOf(Long.valueOf(1)), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(1), Long.class));
assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MAX_VALUE), Long.class));
assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MAX_VALUE + 1), Long.class));
assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MIN_VALUE), Long.class));
assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MIN_VALUE - 1), Long.class));
assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(-1), Long.class)).isEqualTo(Long.valueOf(Long.valueOf(-1)));
assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(0), Long.class)).isEqualTo(Long.valueOf(Long.valueOf(0)));
assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(1), Long.class)).isEqualTo(Long.valueOf(Long.valueOf(1)));
assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MAX_VALUE), Long.class)).isEqualTo(Long.valueOf(Long.MAX_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MAX_VALUE + 1), Long.class)).isEqualTo(Long.valueOf(Long.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MIN_VALUE), Long.class)).isEqualTo(Long.valueOf(Long.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MIN_VALUE - 1), Long.class)).isEqualTo(Long.valueOf(Long.MAX_VALUE));
assertEquals(Long.valueOf(Long.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Long.valueOf(-1), Long.class));
assertEquals(Long.valueOf(Long.valueOf(0)), NumberUtils.convertNumberToTargetClass(Long.valueOf(0), Long.class));
assertEquals(Long.valueOf(Long.valueOf(1)), NumberUtils.convertNumberToTargetClass(Long.valueOf(1), Long.class));
assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MAX_VALUE), Long.class));
assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MAX_VALUE + 1), Long.class));
assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MIN_VALUE), Long.class));
assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MIN_VALUE - 1), Long.class));
assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(-1), Long.class)).isEqualTo(Long.valueOf(Long.valueOf(-1)));
assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(0), Long.class)).isEqualTo(Long.valueOf(Long.valueOf(0)));
assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(1), Long.class)).isEqualTo(Long.valueOf(Long.valueOf(1)));
assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MAX_VALUE), Long.class)).isEqualTo(Long.valueOf(Long.MAX_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MAX_VALUE + 1), Long.class)).isEqualTo(Long.valueOf(Long.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MIN_VALUE), Long.class)).isEqualTo(Long.valueOf(Long.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MIN_VALUE - 1), Long.class)).isEqualTo(Long.valueOf(Long.MAX_VALUE));
assertEquals(Long.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Integer.valueOf(-1), Long.class));
assertEquals(Long.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(Integer.valueOf(0), Long.class));
assertEquals(Long.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(Integer.valueOf(1), Long.class));
assertEquals(Long.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE), Long.class));
assertEquals(Long.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE + 1), Long.class));
assertEquals(Long.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE), Long.class));
assertEquals(Long.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE - 1), Long.class));
assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(-1), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(-1)));
assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(0), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(0)));
assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(1), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(1)));
assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE), Long.class)).isEqualTo(Long.valueOf(Integer.MAX_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE + 1), Long.class)).isEqualTo(Long.valueOf(Integer.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE), Long.class)).isEqualTo(Long.valueOf(Integer.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE - 1), Long.class)).isEqualTo(Long.valueOf(Integer.MAX_VALUE));
assertEquals(Long.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) -1), Long.class));
assertEquals(Long.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 0), Long.class));
assertEquals(Long.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 1), Long.class));
assertEquals(Long.valueOf(Short.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MAX_VALUE), Long.class));
assertEquals(Long.valueOf(Short.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MAX_VALUE + 1)), Long.class));
assertEquals(Long.valueOf(Short.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MIN_VALUE), Long.class));
assertEquals(Long.valueOf(Short.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MIN_VALUE - 1)), Long.class));
assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) -1), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(-1)));
assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 0), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(0)));
assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 1), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(1)));
assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MAX_VALUE), Long.class)).isEqualTo(Long.valueOf(Short.MAX_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MAX_VALUE + 1)), Long.class)).isEqualTo(Long.valueOf(Short.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MIN_VALUE), Long.class)).isEqualTo(Long.valueOf(Short.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MIN_VALUE - 1)), Long.class)).isEqualTo(Long.valueOf(Short.MAX_VALUE));
assertEquals(Long.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) -1), Long.class));
assertEquals(Long.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 0), Long.class));
assertEquals(Long.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 1), Long.class));
assertEquals(Long.valueOf(Byte.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MAX_VALUE), Long.class));
assertEquals(Long.valueOf(Byte.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MAX_VALUE + 1)), Long.class));
assertEquals(Long.valueOf(Byte.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MIN_VALUE), Long.class));
assertEquals(Long.valueOf(Byte.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MIN_VALUE - 1)), Long.class));
assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) -1), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(-1)));
assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 0), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(0)));
assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 1), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(1)));
assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MAX_VALUE), Long.class)).isEqualTo(Long.valueOf(Byte.MAX_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MAX_VALUE + 1)), Long.class)).isEqualTo(Long.valueOf(Byte.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MIN_VALUE), Long.class)).isEqualTo(Long.valueOf(Byte.MIN_VALUE));
assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MIN_VALUE - 1)), Long.class)).isEqualTo(Long.valueOf(Byte.MAX_VALUE));
assertToNumberOverflow(BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE), Long.class);
assertToNumberOverflow(BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE), Long.class);
@@ -370,35 +368,35 @@ public class NumberUtilsTests {
private void assertLongEquals(String aLong) {
assertEquals("Long did not parse", Long.MAX_VALUE, NumberUtils.parseNumber(aLong, Long.class).longValue());
assertThat(NumberUtils.parseNumber(aLong, Long.class).longValue()).as("Long did not parse").isEqualTo(Long.MAX_VALUE);
}
private void assertIntegerEquals(String anInteger) {
assertEquals("Integer did not parse", Integer.MAX_VALUE, NumberUtils.parseNumber(anInteger, Integer.class).intValue());
assertThat(NumberUtils.parseNumber(anInteger, Integer.class).intValue()).as("Integer did not parse").isEqualTo(Integer.MAX_VALUE);
}
private void assertShortEquals(String aShort) {
assertEquals("Short did not parse", Short.MAX_VALUE, NumberUtils.parseNumber(aShort, Short.class).shortValue());
assertThat(NumberUtils.parseNumber(aShort, Short.class).shortValue()).as("Short did not parse").isEqualTo(Short.MAX_VALUE);
}
private void assertByteEquals(String aByte) {
assertEquals("Byte did not parse", Byte.MAX_VALUE, NumberUtils.parseNumber(aByte, Byte.class).byteValue());
assertThat(NumberUtils.parseNumber(aByte, Byte.class).byteValue()).as("Byte did not parse").isEqualTo(Byte.MAX_VALUE);
}
private void assertNegativeLongEquals(String aLong) {
assertEquals("Long did not parse", Long.MIN_VALUE, NumberUtils.parseNumber(aLong, Long.class).longValue());
assertThat(NumberUtils.parseNumber(aLong, Long.class).longValue()).as("Long did not parse").isEqualTo(Long.MIN_VALUE);
}
private void assertNegativeIntegerEquals(String anInteger) {
assertEquals("Integer did not parse", Integer.MIN_VALUE, NumberUtils.parseNumber(anInteger, Integer.class).intValue());
assertThat(NumberUtils.parseNumber(anInteger, Integer.class).intValue()).as("Integer did not parse").isEqualTo(Integer.MIN_VALUE);
}
private void assertNegativeShortEquals(String aShort) {
assertEquals("Short did not parse", Short.MIN_VALUE, NumberUtils.parseNumber(aShort, Short.class).shortValue());
assertThat(NumberUtils.parseNumber(aShort, Short.class).shortValue()).as("Short did not parse").isEqualTo(Short.MIN_VALUE);
}
private void assertNegativeByteEquals(String aByte) {
assertEquals("Byte did not parse", Byte.MIN_VALUE, NumberUtils.parseNumber(aByte, Byte.class).byteValue());
assertThat(NumberUtils.parseNumber(aByte, Byte.class).byteValue()).as("Byte did not parse").isEqualTo(Byte.MIN_VALUE);
}
private void assertToNumberOverflow(Number number, Class<? extends Number> targetClass) {

View File

@@ -28,11 +28,6 @@ import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.util.ObjectUtils.isEmpty;
/**
@@ -47,15 +42,15 @@ public class ObjectUtilsTests {
@Test
public void isCheckedException() {
assertTrue(ObjectUtils.isCheckedException(new Exception()));
assertTrue(ObjectUtils.isCheckedException(new SQLException()));
assertThat(ObjectUtils.isCheckedException(new Exception())).isTrue();
assertThat(ObjectUtils.isCheckedException(new SQLException())).isTrue();
assertFalse(ObjectUtils.isCheckedException(new RuntimeException()));
assertFalse(ObjectUtils.isCheckedException(new IllegalArgumentException("")));
assertThat(ObjectUtils.isCheckedException(new RuntimeException())).isFalse();
assertThat(ObjectUtils.isCheckedException(new IllegalArgumentException(""))).isFalse();
// Any Throwable other than RuntimeException and Error
// has to be considered checked according to the JLS.
assertTrue(ObjectUtils.isCheckedException(new Throwable()));
assertThat(ObjectUtils.isCheckedException(new Throwable())).isTrue();
}
@Test
@@ -65,105 +60,105 @@ public class ObjectUtilsTests {
Class<?>[] sqlAndIO = new Class<?>[] {SQLException.class, IOException.class};
Class<?>[] throwable = new Class<?>[] {Throwable.class};
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException()));
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), empty));
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), exception));
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), sqlAndIO));
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), throwable));
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException())).isTrue();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), empty)).isTrue();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), exception)).isTrue();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), sqlAndIO)).isTrue();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), throwable)).isTrue();
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Exception()));
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), empty));
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), exception));
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), sqlAndIO));
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), throwable));
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Exception())).isFalse();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), empty)).isFalse();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), exception)).isTrue();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), sqlAndIO)).isFalse();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), throwable)).isTrue();
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new SQLException()));
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), empty));
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), exception));
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), sqlAndIO));
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), throwable));
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new SQLException())).isFalse();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), empty)).isFalse();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), exception)).isTrue();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), sqlAndIO)).isTrue();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), throwable)).isTrue();
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Throwable()));
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), empty));
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), exception));
assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), sqlAndIO));
assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), throwable));
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Throwable())).isFalse();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), empty)).isFalse();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), exception)).isFalse();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), sqlAndIO)).isFalse();
assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), throwable)).isTrue();
}
@Test
public void isEmptyNull() {
assertTrue(isEmpty(null));
assertThat(isEmpty(null)).isTrue();
}
@Test
public void isEmptyArray() {
assertTrue(isEmpty(new char[0]));
assertTrue(isEmpty(new Object[0]));
assertTrue(isEmpty(new Integer[0]));
assertThat(isEmpty(new char[0])).isTrue();
assertThat(isEmpty(new Object[0])).isTrue();
assertThat(isEmpty(new Integer[0])).isTrue();
assertFalse(isEmpty(new int[] {42}));
assertFalse(isEmpty(new Integer[] {42}));
assertThat(isEmpty(new int[] {42})).isFalse();
assertThat(isEmpty(new Integer[] {42})).isFalse();
}
@Test
public void isEmptyCollection() {
assertTrue(isEmpty(Collections.emptyList()));
assertTrue(isEmpty(Collections.emptySet()));
assertThat(isEmpty(Collections.emptyList())).isTrue();
assertThat(isEmpty(Collections.emptySet())).isTrue();
Set<String> set = new HashSet<>();
set.add("foo");
assertFalse(isEmpty(set));
assertFalse(isEmpty(Arrays.asList("foo")));
assertThat(isEmpty(set)).isFalse();
assertThat(isEmpty(Arrays.asList("foo"))).isFalse();
}
@Test
public void isEmptyMap() {
assertTrue(isEmpty(Collections.emptyMap()));
assertThat(isEmpty(Collections.emptyMap())).isTrue();
HashMap<String, Object> map = new HashMap<>();
map.put("foo", 42L);
assertFalse(isEmpty(map));
assertThat(isEmpty(map)).isFalse();
}
@Test
public void isEmptyCharSequence() {
assertTrue(isEmpty(new StringBuilder()));
assertTrue(isEmpty(""));
assertThat(isEmpty(new StringBuilder())).isTrue();
assertThat(isEmpty("")).isTrue();
assertFalse(isEmpty(new StringBuilder("foo")));
assertFalse(isEmpty(" "));
assertFalse(isEmpty("\t"));
assertFalse(isEmpty("foo"));
assertThat(isEmpty(new StringBuilder("foo"))).isFalse();
assertThat(isEmpty(" ")).isFalse();
assertThat(isEmpty("\t")).isFalse();
assertThat(isEmpty("foo")).isFalse();
}
@Test
public void isEmptyUnsupportedObjectType() {
assertFalse(isEmpty(42L));
assertFalse(isEmpty(new Object()));
assertThat(isEmpty(42L)).isFalse();
assertThat(isEmpty(new Object())).isFalse();
}
@Test
public void toObjectArray() {
int[] a = new int[] {1, 2, 3, 4, 5};
Integer[] wrapper = (Integer[]) ObjectUtils.toObjectArray(a);
assertTrue(wrapper.length == 5);
assertThat(wrapper.length == 5).isTrue();
for (int i = 0; i < wrapper.length; i++) {
assertEquals(a[i], wrapper[i].intValue());
assertThat(wrapper[i].intValue()).isEqualTo(a[i]);
}
}
@Test
public void toObjectArrayWithNull() {
Object[] objects = ObjectUtils.toObjectArray(null);
assertNotNull(objects);
assertEquals(0, objects.length);
assertThat(objects).isNotNull();
assertThat(objects.length).isEqualTo(0);
}
@Test
public void toObjectArrayWithEmptyPrimitiveArray() {
Object[] objects = ObjectUtils.toObjectArray(new byte[] {});
assertNotNull(objects);
assertEquals(0, objects.length);
assertThat(objects).isNotNull();
assertThat(objects.length).isEqualTo(0);
}
@Test
@@ -175,7 +170,7 @@ public class ObjectUtilsTests {
@Test
public void toObjectArrayWithNonPrimitiveArray() {
String[] source = new String[] {"Bingo"};
assertArrayEquals(source, ObjectUtils.toObjectArray(source));
assertThat(ObjectUtils.toObjectArray(source)).isEqualTo(source);
}
@Test
@@ -183,8 +178,8 @@ public class ObjectUtilsTests {
String[] array = new String[] {"foo", "bar"};
String newElement = "baz";
Object[] newArray = ObjectUtils.addObjectToArray(array, newElement);
assertEquals(3, newArray.length);
assertEquals(newElement, newArray[2]);
assertThat(newArray.length).isEqualTo(3);
assertThat(newArray[2]).isEqualTo(newElement);
}
@Test
@@ -192,8 +187,8 @@ public class ObjectUtilsTests {
String[] array = new String[0];
String newElement = "foo";
String[] newArray = ObjectUtils.addObjectToArray(array, newElement);
assertEquals(1, newArray.length);
assertEquals(newElement, newArray[0]);
assertThat(newArray.length).isEqualTo(1);
assertThat(newArray[0]).isEqualTo(newElement);
}
@Test
@@ -202,9 +197,9 @@ public class ObjectUtilsTests {
String[] array = new String[] {existingElement};
String newElement = "bar";
String[] newArray = ObjectUtils.addObjectToArray(array, newElement);
assertEquals(2, newArray.length);
assertEquals(existingElement, newArray[0]);
assertEquals(newElement, newArray[1]);
assertThat(newArray.length).isEqualTo(2);
assertThat(newArray[0]).isEqualTo(existingElement);
assertThat(newArray[1]).isEqualTo(newElement);
}
@Test
@@ -212,44 +207,44 @@ public class ObjectUtilsTests {
String[] array = new String[] {null};
String newElement = "bar";
String[] newArray = ObjectUtils.addObjectToArray(array, newElement);
assertEquals(2, newArray.length);
assertEquals(null, newArray[0]);
assertEquals(newElement, newArray[1]);
assertThat(newArray.length).isEqualTo(2);
assertThat(newArray[0]).isEqualTo(null);
assertThat(newArray[1]).isEqualTo(newElement);
}
@Test
public void addObjectToNullArray() throws Exception {
String newElement = "foo";
String[] newArray = ObjectUtils.addObjectToArray(null, newElement);
assertEquals(1, newArray.length);
assertEquals(newElement, newArray[0]);
assertThat(newArray.length).isEqualTo(1);
assertThat(newArray[0]).isEqualTo(newElement);
}
@Test
public void addNullObjectToNullArray() throws Exception {
Object[] newArray = ObjectUtils.addObjectToArray(null, null);
assertEquals(1, newArray.length);
assertEquals(null, newArray[0]);
assertThat(newArray.length).isEqualTo(1);
assertThat(newArray[0]).isEqualTo(null);
}
@Test
public void nullSafeEqualsWithArrays() throws Exception {
assertTrue(ObjectUtils.nullSafeEquals(new String[] {"a", "b", "c"}, new String[] {"a", "b", "c"}));
assertTrue(ObjectUtils.nullSafeEquals(new int[] {1, 2, 3}, new int[] {1, 2, 3}));
assertThat(ObjectUtils.nullSafeEquals(new String[] {"a", "b", "c"}, new String[] {"a", "b", "c"})).isTrue();
assertThat(ObjectUtils.nullSafeEquals(new int[] {1, 2, 3}, new int[] {1, 2, 3})).isTrue();
}
@Test
@Deprecated
public void hashCodeWithBooleanFalse() {
int expected = Boolean.FALSE.hashCode();
assertEquals(expected, ObjectUtils.hashCode(false));
assertThat(ObjectUtils.hashCode(false)).isEqualTo(expected);
}
@Test
@Deprecated
public void hashCodeWithBooleanTrue() {
int expected = Boolean.TRUE.hashCode();
assertEquals(expected, ObjectUtils.hashCode(true));
assertThat(ObjectUtils.hashCode(true)).isEqualTo(expected);
}
@Test
@@ -257,7 +252,7 @@ public class ObjectUtilsTests {
public void hashCodeWithDouble() {
double dbl = 9830.43;
int expected = (new Double(dbl)).hashCode();
assertEquals(expected, ObjectUtils.hashCode(dbl));
assertThat(ObjectUtils.hashCode(dbl)).isEqualTo(expected);
}
@Test
@@ -265,7 +260,7 @@ public class ObjectUtilsTests {
public void hashCodeWithFloat() {
float flt = 34.8f;
int expected = (new Float(flt)).hashCode();
assertEquals(expected, ObjectUtils.hashCode(flt));
assertThat(ObjectUtils.hashCode(flt)).isEqualTo(expected);
}
@Test
@@ -273,7 +268,7 @@ public class ObjectUtilsTests {
public void hashCodeWithLong() {
long lng = 883L;
int expected = (new Long(lng)).hashCode();
assertEquals(expected, ObjectUtils.hashCode(lng));
assertThat(ObjectUtils.hashCode(lng)).isEqualTo(expected);
}
@Test
@@ -281,112 +276,112 @@ public class ObjectUtilsTests {
Object obj = new Object();
String expected = obj.getClass().getName() + "@" + ObjectUtils.getIdentityHexString(obj);
String actual = ObjectUtils.identityToString(obj);
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
}
@Test
public void identityToStringWithNullObject() {
assertEquals("", ObjectUtils.identityToString(null));
assertThat(ObjectUtils.identityToString(null)).isEqualTo("");
}
@Test
public void isArrayOfPrimitivesWithBooleanArray() {
assertTrue(ClassUtils.isPrimitiveArray(boolean[].class));
assertThat(ClassUtils.isPrimitiveArray(boolean[].class)).isTrue();
}
@Test
public void isArrayOfPrimitivesWithObjectArray() {
assertFalse(ClassUtils.isPrimitiveArray(Object[].class));
assertThat(ClassUtils.isPrimitiveArray(Object[].class)).isFalse();
}
@Test
public void isArrayOfPrimitivesWithNonArray() {
assertFalse(ClassUtils.isPrimitiveArray(String.class));
assertThat(ClassUtils.isPrimitiveArray(String.class)).isFalse();
}
@Test
public void isPrimitiveOrWrapperWithBooleanPrimitiveClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(boolean.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(boolean.class)).isTrue();
}
@Test
public void isPrimitiveOrWrapperWithBooleanWrapperClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(Boolean.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(Boolean.class)).isTrue();
}
@Test
public void isPrimitiveOrWrapperWithBytePrimitiveClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(byte.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(byte.class)).isTrue();
}
@Test
public void isPrimitiveOrWrapperWithByteWrapperClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(Byte.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(Byte.class)).isTrue();
}
@Test
public void isPrimitiveOrWrapperWithCharacterClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(Character.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(Character.class)).isTrue();
}
@Test
public void isPrimitiveOrWrapperWithCharClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(char.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(char.class)).isTrue();
}
@Test
public void isPrimitiveOrWrapperWithDoublePrimitiveClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(double.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(double.class)).isTrue();
}
@Test
public void isPrimitiveOrWrapperWithDoubleWrapperClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(Double.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(Double.class)).isTrue();
}
@Test
public void isPrimitiveOrWrapperWithFloatPrimitiveClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(float.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(float.class)).isTrue();
}
@Test
public void isPrimitiveOrWrapperWithFloatWrapperClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(Float.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(Float.class)).isTrue();
}
@Test
public void isPrimitiveOrWrapperWithIntClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(int.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(int.class)).isTrue();
}
@Test
public void isPrimitiveOrWrapperWithIntegerClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(Integer.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(Integer.class)).isTrue();
}
@Test
public void isPrimitiveOrWrapperWithLongPrimitiveClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(long.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(long.class)).isTrue();
}
@Test
public void isPrimitiveOrWrapperWithLongWrapperClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(Long.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(Long.class)).isTrue();
}
@Test
public void isPrimitiveOrWrapperWithNonPrimitiveOrWrapperClass() {
assertFalse(ClassUtils.isPrimitiveOrWrapper(Object.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(Object.class)).isFalse();
}
@Test
public void isPrimitiveOrWrapperWithShortPrimitiveClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(short.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(short.class)).isTrue();
}
@Test
public void isPrimitiveOrWrapperWithShortWrapperClass() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(Short.class));
assertThat(ClassUtils.isPrimitiveOrWrapper(Short.class)).isTrue();
}
@Test
@@ -397,12 +392,12 @@ public class ObjectUtilsTests {
boolean[] array = {true, false};
int actual = ObjectUtils.nullSafeHashCode(array);
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
}
@Test
public void nullSafeHashCodeWithBooleanArrayEqualToNull() {
assertEquals(0, ObjectUtils.nullSafeHashCode((boolean[]) null));
assertThat(ObjectUtils.nullSafeHashCode((boolean[]) null)).isEqualTo(0);
}
@Test
@@ -413,12 +408,12 @@ public class ObjectUtilsTests {
byte[] array = {8, 10};
int actual = ObjectUtils.nullSafeHashCode(array);
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
}
@Test
public void nullSafeHashCodeWithByteArrayEqualToNull() {
assertEquals(0, ObjectUtils.nullSafeHashCode((byte[]) null));
assertThat(ObjectUtils.nullSafeHashCode((byte[]) null)).isEqualTo(0);
}
@Test
@@ -429,12 +424,12 @@ public class ObjectUtilsTests {
char[] array = {'a', 'E'};
int actual = ObjectUtils.nullSafeHashCode(array);
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
}
@Test
public void nullSafeHashCodeWithCharArrayEqualToNull() {
assertEquals(0, ObjectUtils.nullSafeHashCode((char[]) null));
assertThat(ObjectUtils.nullSafeHashCode((char[]) null)).isEqualTo(0);
}
@Test
@@ -447,12 +442,12 @@ public class ObjectUtilsTests {
double[] array = {8449.65, 9944.923};
int actual = ObjectUtils.nullSafeHashCode(array);
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
}
@Test
public void nullSafeHashCodeWithDoubleArrayEqualToNull() {
assertEquals(0, ObjectUtils.nullSafeHashCode((double[]) null));
assertThat(ObjectUtils.nullSafeHashCode((double[]) null)).isEqualTo(0);
}
@Test
@@ -463,12 +458,12 @@ public class ObjectUtilsTests {
float[] array = {9.6f, 7.4f};
int actual = ObjectUtils.nullSafeHashCode(array);
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
}
@Test
public void nullSafeHashCodeWithFloatArrayEqualToNull() {
assertEquals(0, ObjectUtils.nullSafeHashCode((float[]) null));
assertThat(ObjectUtils.nullSafeHashCode((float[]) null)).isEqualTo(0);
}
@Test
@@ -479,12 +474,12 @@ public class ObjectUtilsTests {
int[] array = {884, 340};
int actual = ObjectUtils.nullSafeHashCode(array);
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
}
@Test
public void nullSafeHashCodeWithIntArrayEqualToNull() {
assertEquals(0, ObjectUtils.nullSafeHashCode((int[]) null));
assertThat(ObjectUtils.nullSafeHashCode((int[]) null)).isEqualTo(0);
}
@Test
@@ -497,18 +492,18 @@ public class ObjectUtilsTests {
long[] array = {7993L, 84320L};
int actual = ObjectUtils.nullSafeHashCode(array);
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
}
@Test
public void nullSafeHashCodeWithLongArrayEqualToNull() {
assertEquals(0, ObjectUtils.nullSafeHashCode((long[]) null));
assertThat(ObjectUtils.nullSafeHashCode((long[]) null)).isEqualTo(0);
}
@Test
public void nullSafeHashCodeWithObject() {
String str = "Luke";
assertEquals(str.hashCode(), ObjectUtils.nullSafeHashCode(str));
assertThat(ObjectUtils.nullSafeHashCode(str)).isEqualTo(str.hashCode());
}
@Test
@@ -519,12 +514,12 @@ public class ObjectUtilsTests {
Object[] array = {"Leia", "Han"};
int actual = ObjectUtils.nullSafeHashCode(array);
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
}
@Test
public void nullSafeHashCodeWithObjectArrayEqualToNull() {
assertEquals(0, ObjectUtils.nullSafeHashCode((Object[]) null));
assertThat(ObjectUtils.nullSafeHashCode((Object[]) null)).isEqualTo(0);
}
@Test
@@ -592,7 +587,7 @@ public class ObjectUtilsTests {
@Test
public void nullSafeHashCodeWithObjectEqualToNull() {
assertEquals(0, ObjectUtils.nullSafeHashCode((Object) null));
assertThat(ObjectUtils.nullSafeHashCode((Object) null)).isEqualTo(0);
}
@Test
@@ -603,187 +598,187 @@ public class ObjectUtilsTests {
short[] array = {70, 8};
int actual = ObjectUtils.nullSafeHashCode(array);
assertEquals(expected, actual);
assertThat(actual).isEqualTo(expected);
}
@Test
public void nullSafeHashCodeWithShortArrayEqualToNull() {
assertEquals(0, ObjectUtils.nullSafeHashCode((short[]) null));
assertThat(ObjectUtils.nullSafeHashCode((short[]) null)).isEqualTo(0);
}
@Test
public void nullSafeToStringWithBooleanArray() {
boolean[] array = {true, false};
assertEquals("{true, false}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{true, false}");
}
@Test
public void nullSafeToStringWithBooleanArrayBeingEmpty() {
boolean[] array = {};
assertEquals("{}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}");
}
@Test
public void nullSafeToStringWithBooleanArrayEqualToNull() {
assertEquals("null", ObjectUtils.nullSafeToString((boolean[]) null));
assertThat(ObjectUtils.nullSafeToString((boolean[]) null)).isEqualTo("null");
}
@Test
public void nullSafeToStringWithByteArray() {
byte[] array = {5, 8};
assertEquals("{5, 8}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{5, 8}");
}
@Test
public void nullSafeToStringWithByteArrayBeingEmpty() {
byte[] array = {};
assertEquals("{}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}");
}
@Test
public void nullSafeToStringWithByteArrayEqualToNull() {
assertEquals("null", ObjectUtils.nullSafeToString((byte[]) null));
assertThat(ObjectUtils.nullSafeToString((byte[]) null)).isEqualTo("null");
}
@Test
public void nullSafeToStringWithCharArray() {
char[] array = {'A', 'B'};
assertEquals("{'A', 'B'}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{'A', 'B'}");
}
@Test
public void nullSafeToStringWithCharArrayBeingEmpty() {
char[] array = {};
assertEquals("{}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}");
}
@Test
public void nullSafeToStringWithCharArrayEqualToNull() {
assertEquals("null", ObjectUtils.nullSafeToString((char[]) null));
assertThat(ObjectUtils.nullSafeToString((char[]) null)).isEqualTo("null");
}
@Test
public void nullSafeToStringWithDoubleArray() {
double[] array = {8594.93, 8594023.95};
assertEquals("{8594.93, 8594023.95}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{8594.93, 8594023.95}");
}
@Test
public void nullSafeToStringWithDoubleArrayBeingEmpty() {
double[] array = {};
assertEquals("{}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}");
}
@Test
public void nullSafeToStringWithDoubleArrayEqualToNull() {
assertEquals("null", ObjectUtils.nullSafeToString((double[]) null));
assertThat(ObjectUtils.nullSafeToString((double[]) null)).isEqualTo("null");
}
@Test
public void nullSafeToStringWithFloatArray() {
float[] array = {8.6f, 43.8f};
assertEquals("{8.6, 43.8}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{8.6, 43.8}");
}
@Test
public void nullSafeToStringWithFloatArrayBeingEmpty() {
float[] array = {};
assertEquals("{}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}");
}
@Test
public void nullSafeToStringWithFloatArrayEqualToNull() {
assertEquals("null", ObjectUtils.nullSafeToString((float[]) null));
assertThat(ObjectUtils.nullSafeToString((float[]) null)).isEqualTo("null");
}
@Test
public void nullSafeToStringWithIntArray() {
int[] array = {9, 64};
assertEquals("{9, 64}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{9, 64}");
}
@Test
public void nullSafeToStringWithIntArrayBeingEmpty() {
int[] array = {};
assertEquals("{}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}");
}
@Test
public void nullSafeToStringWithIntArrayEqualToNull() {
assertEquals("null", ObjectUtils.nullSafeToString((int[]) null));
assertThat(ObjectUtils.nullSafeToString((int[]) null)).isEqualTo("null");
}
@Test
public void nullSafeToStringWithLongArray() {
long[] array = {434L, 23423L};
assertEquals("{434, 23423}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{434, 23423}");
}
@Test
public void nullSafeToStringWithLongArrayBeingEmpty() {
long[] array = {};
assertEquals("{}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}");
}
@Test
public void nullSafeToStringWithLongArrayEqualToNull() {
assertEquals("null", ObjectUtils.nullSafeToString((long[]) null));
assertThat(ObjectUtils.nullSafeToString((long[]) null)).isEqualTo("null");
}
@Test
public void nullSafeToStringWithPlainOldString() {
assertEquals("I shoh love tha taste of mangoes", ObjectUtils.nullSafeToString("I shoh love tha taste of mangoes"));
assertThat(ObjectUtils.nullSafeToString("I shoh love tha taste of mangoes")).isEqualTo("I shoh love tha taste of mangoes");
}
@Test
public void nullSafeToStringWithObjectArray() {
Object[] array = {"Han", Long.valueOf(43)};
assertEquals("{Han, 43}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{Han, 43}");
}
@Test
public void nullSafeToStringWithObjectArrayBeingEmpty() {
Object[] array = {};
assertEquals("{}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}");
}
@Test
public void nullSafeToStringWithObjectArrayEqualToNull() {
assertEquals("null", ObjectUtils.nullSafeToString((Object[]) null));
assertThat(ObjectUtils.nullSafeToString((Object[]) null)).isEqualTo("null");
}
@Test
public void nullSafeToStringWithShortArray() {
short[] array = {7, 9};
assertEquals("{7, 9}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{7, 9}");
}
@Test
public void nullSafeToStringWithShortArrayBeingEmpty() {
short[] array = {};
assertEquals("{}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}");
}
@Test
public void nullSafeToStringWithShortArrayEqualToNull() {
assertEquals("null", ObjectUtils.nullSafeToString((short[]) null));
assertThat(ObjectUtils.nullSafeToString((short[]) null)).isEqualTo("null");
}
@Test
public void nullSafeToStringWithStringArray() {
String[] array = {"Luke", "Anakin"};
assertEquals("{Luke, Anakin}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{Luke, Anakin}");
}
@Test
public void nullSafeToStringWithStringArrayBeingEmpty() {
String[] array = {};
assertEquals("{}", ObjectUtils.nullSafeToString(array));
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}");
}
@Test
public void nullSafeToStringWithStringArrayEqualToNull() {
assertEquals("null", ObjectUtils.nullSafeToString((String[]) null));
assertThat(ObjectUtils.nullSafeToString((String[]) null)).isEqualTo("null");
}
@Test
@@ -813,8 +808,8 @@ public class ObjectUtilsTests {
private void assertEqualHashCodes(int expected, Object array) {
int actual = ObjectUtils.nullSafeHashCode(array);
assertEquals(expected, actual);
assertTrue(array.hashCode() != actual);
assertThat(actual).isEqualTo(expected);
assertThat(array.hashCode() != actual).isTrue();
}

View File

@@ -18,7 +18,7 @@ package org.springframework.util;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Juergen Hoeller
@@ -28,8 +28,8 @@ public class PatternMatchUtilsTests {
@Test
public void testTrivial() {
assertEquals(false, PatternMatchUtils.simpleMatch((String) null, ""));
assertEquals(false, PatternMatchUtils.simpleMatch("1", null));
assertThat(PatternMatchUtils.simpleMatch((String) null, "")).isEqualTo(false);
assertThat(PatternMatchUtils.simpleMatch("1", null)).isEqualTo(false);
doTest("*", "123", true);
doTest("123", "123", true);
}
@@ -100,7 +100,7 @@ public class PatternMatchUtilsTests {
}
private void doTest(String pattern, String str, boolean shouldMatch) {
assertEquals(shouldMatch, PatternMatchUtils.simpleMatch(pattern, str));
assertThat(PatternMatchUtils.simpleMatch(pattern, str)).isEqualTo(shouldMatch);
}
}

View File

@@ -25,8 +25,7 @@ import java.util.Properties;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Juergen Hoeller
@@ -107,8 +106,8 @@ public class PropertiesPersisterTests {
else {
persister.load(props, new ByteArrayInputStream(propString.getBytes()));
}
assertEquals("message1", props.getProperty("code1"));
assertEquals("message2", props.getProperty("code2"));
assertThat(props.getProperty("code1")).isEqualTo("message1");
assertThat(props.getProperty("code2")).isEqualTo("message2");
return props;
}
@@ -126,10 +125,10 @@ public class PropertiesPersisterTests {
propCopy = new String(propOut.toByteArray());
}
if (header != null) {
assertTrue(propCopy.contains(header));
assertThat(propCopy.contains(header)).isTrue();
}
assertTrue(propCopy.contains("\ncode1=message1"));
assertTrue(propCopy.contains("\ncode2=message2"));
assertThat(propCopy.contains("\ncode1=message1")).isTrue();
assertThat(propCopy.contains("\ncode2=message2")).isTrue();
return propCopy;
}

View File

@@ -20,8 +20,10 @@ import java.util.Properties;
import org.junit.Test;
import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
/**
* @author Rob Harrop
@@ -36,7 +38,7 @@ public class PropertyPlaceholderHelperTests {
Properties props = new Properties();
props.setProperty("foo", "bar");
assertEquals("foo=bar", this.helper.replacePlaceholders(text, props));
assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("foo=bar");
}
@Test
@@ -46,7 +48,7 @@ public class PropertyPlaceholderHelperTests {
props.setProperty("foo", "bar");
props.setProperty("bar", "baz");
assertEquals("foo=bar,bar=baz", this.helper.replacePlaceholders(text, props));
assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("foo=bar,bar=baz");
}
@Test
@@ -56,7 +58,7 @@ public class PropertyPlaceholderHelperTests {
props.setProperty("bar", "${baz}");
props.setProperty("baz", "bar");
assertEquals("foo=bar", this.helper.replacePlaceholders(text, props));
assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("foo=bar");
}
@Test
@@ -66,7 +68,7 @@ public class PropertyPlaceholderHelperTests {
props.setProperty("bar", "bar");
props.setProperty("inner", "ar");
assertEquals("foo=bar", this.helper.replacePlaceholders(text, props));
assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("foo=bar");
text = "${top}";
props = new Properties();
@@ -75,25 +77,21 @@ public class PropertyPlaceholderHelperTests {
props.setProperty("differentiator", "first");
props.setProperty("first.grandchild", "actualValue");
assertEquals("actualValue+actualValue", this.helper.replacePlaceholders(text, props));
assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("actualValue+actualValue");
}
@Test
public void testWithResolver() {
String text = "foo=${foo}";
PlaceholderResolver resolver = new PlaceholderResolver() {
assertEquals("foo=bar",
this.helper.replacePlaceholders(text, new PropertyPlaceholderHelper.PlaceholderResolver() {
@Override
public String resolvePlaceholder(String placeholderName) {
if ("foo".equals(placeholderName)) {
return "bar";
}
else {
return null;
}
}
}));
@Override
public String resolvePlaceholder(String placeholderName) {
return "foo".equals(placeholderName) ? "bar" : null;
}
};
assertThat(this.helper.replacePlaceholders(text, resolver)).isEqualTo("foo=bar");
}
@Test
@@ -102,7 +100,7 @@ public class PropertyPlaceholderHelperTests {
Properties props = new Properties();
props.setProperty("foo", "bar");
assertEquals("foo=bar,bar=${bar}", this.helper.replacePlaceholders(text, props));
assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("foo=bar,bar=${bar}");
}
@Test

View File

@@ -33,11 +33,6 @@ 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.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* @author Rob Harrop
@@ -50,22 +45,22 @@ public class ReflectionUtilsTests {
@Test
public void findField() {
Field field = ReflectionUtils.findField(TestObjectSubclassWithPublicField.class, "publicField", String.class);
assertNotNull(field);
assertEquals("publicField", field.getName());
assertEquals(String.class, field.getType());
assertTrue("Field should be public.", Modifier.isPublic(field.getModifiers()));
assertThat(field).isNotNull();
assertThat(field.getName()).isEqualTo("publicField");
assertThat(field.getType()).isEqualTo(String.class);
assertThat(Modifier.isPublic(field.getModifiers())).as("Field should be public.").isTrue();
field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "prot", String.class);
assertNotNull(field);
assertEquals("prot", field.getName());
assertEquals(String.class, field.getType());
assertTrue("Field should be protected.", Modifier.isProtected(field.getModifiers()));
assertThat(field).isNotNull();
assertThat(field.getName()).isEqualTo("prot");
assertThat(field.getType()).isEqualTo(String.class);
assertThat(Modifier.isProtected(field.getModifiers())).as("Field should be protected.").isTrue();
field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class);
assertNotNull(field);
assertEquals("name", field.getName());
assertEquals(String.class, field.getType());
assertTrue("Field should be private.", Modifier.isPrivate(field.getModifiers()));
assertThat(field).isNotNull();
assertThat(field.getName()).isEqualTo("name");
assertThat(field.getType()).isEqualTo(String.class);
assertThat(Modifier.isPrivate(field.getModifiers())).as("Field should be private.").isTrue();
}
@Test
@@ -76,11 +71,11 @@ public class ReflectionUtilsTests {
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, testBean, "FooBar");
assertNotNull(testBean.getName());
assertEquals("FooBar", testBean.getName());
assertThat(testBean.getName()).isNotNull();
assertThat(testBean.getName()).isEqualTo("FooBar");
ReflectionUtils.setField(field, testBean, null);
assertNull(testBean.getName());
assertThat((Object) testBean.getName()).isNull();
}
@Test
@@ -94,26 +89,26 @@ public class ReflectionUtilsTests {
Method setName = TestObject.class.getMethod("setName", String.class);
Object name = ReflectionUtils.invokeMethod(getName, bean);
assertEquals("Incorrect name returned", rob, name);
assertThat(name).as("Incorrect name returned").isEqualTo(rob);
String juergen = "Juergen Hoeller";
ReflectionUtils.invokeMethod(setName, bean, juergen);
assertEquals("Incorrect name set", juergen, bean.getName());
assertThat(bean.getName()).as("Incorrect name set").isEqualTo(juergen);
}
@Test
public void declaresException() throws Exception {
Method remoteExMethod = A.class.getDeclaredMethod("foo", Integer.class);
assertTrue(ReflectionUtils.declaresException(remoteExMethod, RemoteException.class));
assertTrue(ReflectionUtils.declaresException(remoteExMethod, ConnectException.class));
assertFalse(ReflectionUtils.declaresException(remoteExMethod, NoSuchMethodException.class));
assertFalse(ReflectionUtils.declaresException(remoteExMethod, Exception.class));
assertThat(ReflectionUtils.declaresException(remoteExMethod, RemoteException.class)).isTrue();
assertThat(ReflectionUtils.declaresException(remoteExMethod, ConnectException.class)).isTrue();
assertThat(ReflectionUtils.declaresException(remoteExMethod, NoSuchMethodException.class)).isFalse();
assertThat(ReflectionUtils.declaresException(remoteExMethod, Exception.class)).isFalse();
Method illegalExMethod = B.class.getDeclaredMethod("bar", String.class);
assertTrue(ReflectionUtils.declaresException(illegalExMethod, IllegalArgumentException.class));
assertTrue(ReflectionUtils.declaresException(illegalExMethod, NumberFormatException.class));
assertFalse(ReflectionUtils.declaresException(illegalExMethod, IllegalStateException.class));
assertFalse(ReflectionUtils.declaresException(illegalExMethod, Exception.class));
assertThat(ReflectionUtils.declaresException(illegalExMethod, IllegalArgumentException.class)).isTrue();
assertThat(ReflectionUtils.declaresException(illegalExMethod, NumberFormatException.class)).isTrue();
assertThat(ReflectionUtils.declaresException(illegalExMethod, IllegalStateException.class)).isFalse();
assertThat(ReflectionUtils.declaresException(illegalExMethod, Exception.class)).isFalse();
}
@Test
@@ -157,8 +152,8 @@ public class ReflectionUtilsTests {
testValidCopy(src, dest);
// Check subclass fields were copied
assertEquals(src.magic, dest.magic);
assertEquals(src.prot, dest.prot);
assertThat(dest.magic).isEqualTo(src.magic);
assertThat(dest.prot).isEqualTo(src.prot);
}
@Test
@@ -168,7 +163,7 @@ public class ReflectionUtilsTests {
dest.magic = 11;
testValidCopy(src, dest);
// Should have left this one alone
assertEquals(11, dest.magic);
assertThat(dest.magic).isEqualTo(11);
}
@Test
@@ -183,11 +178,11 @@ public class ReflectionUtilsTests {
src.setName("freddie");
src.setAge(15);
src.setSpouse(new TestObject());
assertFalse(src.getAge() == dest.getAge());
assertThat(src.getAge() == dest.getAge()).isFalse();
ReflectionUtils.shallowCopyFieldState(src, dest);
assertEquals(src.getAge(), dest.getAge());
assertEquals(src.getSpouse(), dest.getSpouse());
assertThat(dest.getAge()).isEqualTo(src.getAge());
assertThat(dest.getSpouse()).isEqualTo(src.getSpouse());
}
@Test
@@ -199,11 +194,11 @@ public class ReflectionUtilsTests {
return Modifier.isProtected(m.getModifiers());
}
});
assertFalse(mc.getMethodNames().isEmpty());
assertTrue("Must find protected method on Object", mc.getMethodNames().contains("clone"));
assertTrue("Must find protected method on Object", mc.getMethodNames().contains("finalize"));
assertFalse("Public, not protected", mc.getMethodNames().contains("hashCode"));
assertFalse("Public, not protected", mc.getMethodNames().contains("absquatulate"));
assertThat(mc.getMethodNames().isEmpty()).isFalse();
assertThat(mc.getMethodNames().contains("clone")).as("Must find protected method on Object").isTrue();
assertThat(mc.getMethodNames().contains("finalize")).as("Must find protected method on Object").isTrue();
assertThat(mc.getMethodNames().contains("hashCode")).as("Public, not protected").isFalse();
assertThat(mc.getMethodNames().contains("absquatulate")).as("Public, not protected").isFalse();
}
@Test
@@ -216,20 +211,20 @@ public class ReflectionUtilsTests {
++absquatulateCount;
}
}
assertEquals("Found 2 absquatulates", 2, absquatulateCount);
assertThat(absquatulateCount).as("Found 2 absquatulates").isEqualTo(2);
}
@Test
public void findMethod() throws Exception {
assertNotNull(ReflectionUtils.findMethod(B.class, "bar", String.class));
assertNotNull(ReflectionUtils.findMethod(B.class, "foo", Integer.class));
assertNotNull(ReflectionUtils.findMethod(B.class, "getClass"));
assertThat(ReflectionUtils.findMethod(B.class, "bar", String.class)).isNotNull();
assertThat(ReflectionUtils.findMethod(B.class, "foo", Integer.class)).isNotNull();
assertThat(ReflectionUtils.findMethod(B.class, "getClass")).isNotNull();
}
@Ignore("[SPR-8644] findMethod() does not currently support var-args")
@Test
public void findMethodWithVarArgs() throws Exception {
assertNotNull(ReflectionUtils.findMethod(B.class, "add", int.class, int.class, int.class));
assertThat(ReflectionUtils.findMethod(B.class, "add", int.class, int.class, int.class)).isNotNull();
}
@Test
@@ -260,14 +255,14 @@ public class ReflectionUtilsTests {
public void m1$1() {
}
}
assertTrue(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$123")));
assertTrue(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$0")));
assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$$0")));
assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$")));
assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1")));
assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1")));
assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1$")));
assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1$1")));
assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$123"))).isTrue();
assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$0"))).isTrue();
assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$$0"))).isFalse();
assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$"))).isFalse();
assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1"))).isFalse();
assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1"))).isFalse();
assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1$"))).isFalse();
assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1$1"))).isFalse();
}
@Test
@@ -326,8 +321,8 @@ public class ReflectionUtilsTests {
}
}
assertThat(m1MethodCount).isEqualTo(1);
assertTrue(ObjectUtils.containsElement(methods, Leaf.class.getMethod("m1")));
assertFalse(ObjectUtils.containsElement(methods, Parent.class.getMethod("m1")));
assertThat(ObjectUtils.containsElement(methods, Leaf.class.getMethod("m1"))).isTrue();
assertThat(ObjectUtils.containsElement(methods, Parent.class.getMethod("m1"))).isFalse();
}
@Test

View File

@@ -19,9 +19,8 @@ package org.springframework.util;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
/**
* @author Brian Clozel
@@ -45,29 +44,29 @@ public class ResizableByteArrayOutputStreamTests {
@Test
public void resize() throws Exception {
assertEquals(INITIAL_CAPACITY, this.baos.capacity());
assertThat(this.baos.capacity()).isEqualTo(INITIAL_CAPACITY);
this.baos.write(helloBytes);
int size = 64;
this.baos.resize(size);
assertEquals(size, this.baos.capacity());
assertThat(this.baos.capacity()).isEqualTo(size);
assertByteArrayEqualsString(this.baos);
}
@Test
public void autoGrow() {
assertEquals(INITIAL_CAPACITY, this.baos.capacity());
assertThat(this.baos.capacity()).isEqualTo(INITIAL_CAPACITY);
for (int i = 0; i < 129; i++) {
this.baos.write(0);
}
assertEquals(256, this.baos.capacity());
assertThat(this.baos.capacity()).isEqualTo(256);
}
@Test
public void grow() throws Exception {
assertEquals(INITIAL_CAPACITY, this.baos.capacity());
assertThat(this.baos.capacity()).isEqualTo(INITIAL_CAPACITY);
this.baos.write(helloBytes);
this.baos.grow(1000);
assertEquals(this.helloBytes.length + 1000, this.baos.capacity());
assertThat(this.baos.capacity()).isEqualTo((this.helloBytes.length + 1000));
assertByteArrayEqualsString(this.baos);
}
@@ -86,7 +85,7 @@ public class ResizableByteArrayOutputStreamTests {
private void assertByteArrayEqualsString(ResizableByteArrayOutputStream actual) {
assertArrayEquals(helloBytes, actual.toByteArray());
assertThat(actual.toByteArray()).isEqualTo(helloBytes);
}
}

View File

@@ -23,9 +23,7 @@ import java.net.URLStreamHandler;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Juergen Hoeller
@@ -34,58 +32,40 @@ public class ResourceUtilsTests {
@Test
public void isJarURL() throws Exception {
assertTrue(ResourceUtils.isJarURL(new URL("jar:file:myjar.jar!/mypath")));
assertTrue(ResourceUtils.isJarURL(new URL(null, "zip:file:myjar.jar!/mypath", new DummyURLStreamHandler())));
assertTrue(ResourceUtils.isJarURL(new URL(null, "wsjar:file:myjar.jar!/mypath", new DummyURLStreamHandler())));
assertTrue(ResourceUtils.isJarURL(new URL(null, "jar:war:file:mywar.war*/myjar.jar!/mypath", new DummyURLStreamHandler())));
assertFalse(ResourceUtils.isJarURL(new URL("file:myjar.jar")));
assertFalse(ResourceUtils.isJarURL(new URL("http:myserver/myjar.jar")));
assertThat(ResourceUtils.isJarURL(new URL("jar:file:myjar.jar!/mypath"))).isTrue();
assertThat(ResourceUtils.isJarURL(new URL(null, "zip:file:myjar.jar!/mypath", new DummyURLStreamHandler()))).isTrue();
assertThat(ResourceUtils.isJarURL(new URL(null, "wsjar:file:myjar.jar!/mypath", new DummyURLStreamHandler()))).isTrue();
assertThat(ResourceUtils.isJarURL(new URL(null, "jar:war:file:mywar.war*/myjar.jar!/mypath", new DummyURLStreamHandler()))).isTrue();
assertThat(ResourceUtils.isJarURL(new URL("file:myjar.jar"))).isFalse();
assertThat(ResourceUtils.isJarURL(new URL("http:myserver/myjar.jar"))).isFalse();
}
@Test
public void extractJarFileURL() throws Exception {
assertEquals(new URL("file:myjar.jar"),
ResourceUtils.extractJarFileURL(new URL("jar:file:myjar.jar!/mypath")));
assertEquals(new URL("file:/myjar.jar"),
ResourceUtils.extractJarFileURL(new URL(null, "jar:myjar.jar!/mypath", new DummyURLStreamHandler())));
assertEquals(new URL("file:myjar.jar"),
ResourceUtils.extractJarFileURL(new URL(null, "zip:file:myjar.jar!/mypath", new DummyURLStreamHandler())));
assertEquals(new URL("file:myjar.jar"),
ResourceUtils.extractJarFileURL(new URL(null, "wsjar:file:myjar.jar!/mypath", new DummyURLStreamHandler())));
assertThat(ResourceUtils.extractJarFileURL(new URL("jar:file:myjar.jar!/mypath"))).isEqualTo(new URL("file:myjar.jar"));
assertThat(ResourceUtils.extractJarFileURL(new URL(null, "jar:myjar.jar!/mypath", new DummyURLStreamHandler()))).isEqualTo(new URL("file:/myjar.jar"));
assertThat(ResourceUtils.extractJarFileURL(new URL(null, "zip:file:myjar.jar!/mypath", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar"));
assertThat(ResourceUtils.extractJarFileURL(new URL(null, "wsjar:file:myjar.jar!/mypath", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar"));
assertEquals(new URL("file:myjar.jar"),
ResourceUtils.extractJarFileURL(new URL("file:myjar.jar")));
assertEquals(new URL("file:myjar.jar"),
ResourceUtils.extractJarFileURL(new URL("jar:file:myjar.jar!/")));
assertEquals(new URL("file:myjar.jar"),
ResourceUtils.extractJarFileURL(new URL(null, "zip:file:myjar.jar!/", new DummyURLStreamHandler())));
assertEquals(new URL("file:myjar.jar"),
ResourceUtils.extractJarFileURL(new URL(null, "wsjar:file:myjar.jar!/", new DummyURLStreamHandler())));
assertThat(ResourceUtils.extractJarFileURL(new URL("file:myjar.jar"))).isEqualTo(new URL("file:myjar.jar"));
assertThat(ResourceUtils.extractJarFileURL(new URL("jar:file:myjar.jar!/"))).isEqualTo(new URL("file:myjar.jar"));
assertThat(ResourceUtils.extractJarFileURL(new URL(null, "zip:file:myjar.jar!/", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar"));
assertThat(ResourceUtils.extractJarFileURL(new URL(null, "wsjar:file:myjar.jar!/", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar"));
}
@Test
public void extractArchiveURL() throws Exception {
assertEquals(new URL("file:myjar.jar"),
ResourceUtils.extractArchiveURL(new URL("jar:file:myjar.jar!/mypath")));
assertEquals(new URL("file:/myjar.jar"),
ResourceUtils.extractArchiveURL(new URL(null, "jar:myjar.jar!/mypath", new DummyURLStreamHandler())));
assertEquals(new URL("file:myjar.jar"),
ResourceUtils.extractArchiveURL(new URL(null, "zip:file:myjar.jar!/mypath", new DummyURLStreamHandler())));
assertEquals(new URL("file:myjar.jar"),
ResourceUtils.extractArchiveURL(new URL(null, "wsjar:file:myjar.jar!/mypath", new DummyURLStreamHandler())));
assertEquals(new URL("file:mywar.war"),
ResourceUtils.extractArchiveURL(new URL(null, "jar:war:file:mywar.war*/myjar.jar!/mypath", new DummyURLStreamHandler())));
assertThat(ResourceUtils.extractArchiveURL(new URL("jar:file:myjar.jar!/mypath"))).isEqualTo(new URL("file:myjar.jar"));
assertThat(ResourceUtils.extractArchiveURL(new URL(null, "jar:myjar.jar!/mypath", new DummyURLStreamHandler()))).isEqualTo(new URL("file:/myjar.jar"));
assertThat(ResourceUtils.extractArchiveURL(new URL(null, "zip:file:myjar.jar!/mypath", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar"));
assertThat(ResourceUtils.extractArchiveURL(new URL(null, "wsjar:file:myjar.jar!/mypath", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar"));
assertThat(ResourceUtils.extractArchiveURL(new URL(null, "jar:war:file:mywar.war*/myjar.jar!/mypath", new DummyURLStreamHandler()))).isEqualTo(new URL("file:mywar.war"));
assertEquals(new URL("file:myjar.jar"),
ResourceUtils.extractArchiveURL(new URL("file:myjar.jar")));
assertEquals(new URL("file:myjar.jar"),
ResourceUtils.extractArchiveURL(new URL("jar:file:myjar.jar!/")));
assertEquals(new URL("file:myjar.jar"),
ResourceUtils.extractArchiveURL(new URL(null, "zip:file:myjar.jar!/", new DummyURLStreamHandler())));
assertEquals(new URL("file:myjar.jar"),
ResourceUtils.extractArchiveURL(new URL(null, "wsjar:file:myjar.jar!/", new DummyURLStreamHandler())));
assertEquals(new URL("file:mywar.war"),
ResourceUtils.extractArchiveURL(new URL(null, "jar:war:file:mywar.war*/myjar.jar!/", new DummyURLStreamHandler())));
assertThat(ResourceUtils.extractArchiveURL(new URL("file:myjar.jar"))).isEqualTo(new URL("file:myjar.jar"));
assertThat(ResourceUtils.extractArchiveURL(new URL("jar:file:myjar.jar!/"))).isEqualTo(new URL("file:myjar.jar"));
assertThat(ResourceUtils.extractArchiveURL(new URL(null, "zip:file:myjar.jar!/", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar"));
assertThat(ResourceUtils.extractArchiveURL(new URL(null, "wsjar:file:myjar.jar!/", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar"));
assertThat(ResourceUtils.extractArchiveURL(new URL(null, "jar:war:file:mywar.war*/myjar.jar!/", new DummyURLStreamHandler()))).isEqualTo(new URL("file:mywar.war"));
}

View File

@@ -20,10 +20,9 @@ import java.math.BigInteger;
import org.junit.Test;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* Test for static utility to help with serialization.
@@ -40,7 +39,7 @@ public class SerializationUtilsTests {
@Test
public void serializeCycleSunnyDay() throws Exception {
assertEquals("foo", SerializationUtils.deserialize(SerializationUtils.serialize("foo")));
assertThat(SerializationUtils.deserialize(SerializationUtils.serialize("foo"))).isEqualTo("foo");
}
@Test
@@ -64,12 +63,12 @@ public class SerializationUtilsTests {
@Test
public void serializeNull() throws Exception {
assertNull(SerializationUtils.serialize(null));
assertThat(SerializationUtils.serialize(null)).isNull();
}
@Test
public void deserializeNull() throws Exception {
assertNull(SerializationUtils.deserialize(null));
assertThat(SerializationUtils.deserialize(null)).isNull();
}
}

View File

@@ -24,10 +24,9 @@ import javax.net.ServerSocketFactory;
import org.junit.Test;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.springframework.util.SocketUtils.PORT_RANGE_MAX;
import static org.springframework.util.SocketUtils.PORT_RANGE_MIN;
@@ -71,7 +70,7 @@ public class SocketUtilsTests {
public void findAvailableTcpPortWithMinPortEqualToMaxPort() {
int minMaxPort = SocketUtils.findAvailableTcpPort();
int port = SocketUtils.findAvailableTcpPort(minMaxPort, minMaxPort);
assertEquals(minMaxPort, port);
assertThat(port).isEqualTo(minMaxPort);
}
@Test
@@ -230,12 +229,12 @@ public class SocketUtilsTests {
assertAvailablePorts(ports, numRequested, minPort, maxPort);
}
private void assertPortInRange(int port, int minPort, int maxPort) {
assertTrue("port [" + port + "] >= " + minPort, port >= minPort);
assertTrue("port [" + port + "] <= " + maxPort, port <= maxPort);
assertThat(port >= minPort).as("port [" + port + "] >= " + minPort).isTrue();
assertThat(port <= maxPort).as("port [" + port + "] <= " + maxPort).isTrue();
}
private void assertAvailablePorts(SortedSet<Integer> ports, int numRequested, int minPort, int maxPort) {
assertEquals("number of ports requested", numRequested, ports.size());
assertThat(ports.size()).as("number of ports requested").isEqualTo(numRequested);
for (int port : ports) {
assertPortInRange(port, minPort, maxPort);
}

Some files were not shown because too many files have changed in this diff Show More