Migrate exception checking tests to use AssertJ

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

View File

@ -23,9 +23,9 @@ import org.junit.Test;
import org.springframework.aop.aspectj.AspectJAdviceParameterNameDiscoverer.AmbiguousBindingException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
/**
* Unit tests for the {@link AspectJAdviceParameterNameDiscoverer} class.
@ -226,8 +226,7 @@ public class AspectJAdviceParameterNameDiscovererTests {
return candidate;
}
}
fail("Bad test specification, no method '" + name + "' found in test class");
return null;
throw new AssertionError("Bad test specification, no method '" + name + "' found in test class");
}
protected void assertParameterNames(Method method, String pointcut, String[] parameterNames) {
@ -262,27 +261,20 @@ public class AspectJAdviceParameterNameDiscovererTests {
}
}
protected void assertException(Method method, String pointcut, Class<?> exceptionType, String message) {
protected void assertException(Method method, String pointcut, Class<? extends Throwable> exceptionType, String message) {
assertException(method, pointcut, null, null, exceptionType, message);
}
protected void assertException(
Method method, String pointcut, String returning, String throwing, Class<?> exceptionType, String message) {
protected void assertException(Method method, String pointcut, String returning,
String throwing, Class<? extends Throwable> exceptionType, String message) {
AspectJAdviceParameterNameDiscoverer discoverer = new AspectJAdviceParameterNameDiscoverer(pointcut);
discoverer.setRaiseExceptions(true);
discoverer.setReturningName(returning);
discoverer.setThrowingName(throwing);
try {
discoverer.getParameterNames(method);
fail("Expecting " + exceptionType.getName() + " with message '" + message + "'");
}
catch (RuntimeException expected) {
assertEquals("Expecting exception of type " + exceptionType.getName(),
exceptionType, expected.getClass());
assertEquals("Exception message does not match expected", message, expected.getMessage());
}
assertThatExceptionOfType(exceptionType).isThrownBy(() ->
discoverer.getParameterNames(method))
.withMessageContaining(message);
}

View File

@ -36,10 +36,13 @@ import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.tests.sample.beans.subpkg.DeepBean;
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;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@ -163,37 +166,25 @@ public class AspectJExpressionPointcutTests {
@Test
public void testFriendlyErrorOnNoLocationClassMatching() {
AspectJExpressionPointcut pc = new AspectJExpressionPointcut();
try {
pc.matches(ITestBean.class);
fail();
}
catch (IllegalStateException ex) {
assertTrue(ex.getMessage().contains("expression"));
}
assertThatIllegalStateException().isThrownBy(() ->
pc.matches(ITestBean.class))
.withMessageContaining("expression");
}
@Test
public void testFriendlyErrorOnNoLocation2ArgMatching() {
AspectJExpressionPointcut pc = new AspectJExpressionPointcut();
try {
pc.matches(getAge, ITestBean.class);
fail();
}
catch (IllegalStateException ex) {
assertTrue(ex.getMessage().contains("expression"));
}
assertThatIllegalStateException().isThrownBy(() ->
pc.matches(getAge, ITestBean.class))
.withMessageContaining("expression");
}
@Test
public void testFriendlyErrorOnNoLocation3ArgMatching() {
AspectJExpressionPointcut pc = new AspectJExpressionPointcut();
try {
pc.matches(getAge, ITestBean.class, (Object[]) null);
fail();
}
catch (IllegalStateException ex) {
assertTrue(ex.getMessage().contains("expression"));
}
assertThatIllegalStateException().isThrownBy(() ->
pc.matches(getAge, ITestBean.class, (Object[]) null))
.withMessageContaining("expression");
}
@ -248,14 +239,8 @@ public class AspectJExpressionPointcutTests {
@Test
public void testInvalidExpression() {
String expression = "execution(void org.springframework.tests.sample.beans.TestBean.setSomeNumber(Number) && args(Double)";
try {
getPointcut(expression).getClassFilter(); // call to getClassFilter forces resolution
fail("Invalid expression should throw IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
assertTrue(true);
}
assertThatIllegalArgumentException().isThrownBy(
getPointcut(expression)::getClassFilter); // call to getClassFilter forces resolution
}
private TestBean getAdvisedProxy(String pointcutExpression, CallCountingInterceptor interceptor) {
@ -285,14 +270,9 @@ public class AspectJExpressionPointcutTests {
@Test
public void testWithUnsupportedPointcutPrimitive() {
String expression = "call(int org.springframework.tests.sample.beans.TestBean.getAge())";
try {
getPointcut(expression).getClassFilter(); // call to getClassFilter forces resolution...
fail("Should not support call pointcuts");
}
catch (UnsupportedPointcutPrimitiveException ex) {
assertEquals("Should not support call pointcut", PointcutPrimitive.CALL, ex.getUnsupportedPrimitive());
}
assertThatExceptionOfType(UnsupportedPointcutPrimitiveException.class).isThrownBy(() ->
getPointcut(expression).getClassFilter()) // call to getClassFilter forces resolution...
.satisfies(ex -> assertThat(ex.getUnsupportedPrimitive()).isEqualTo(PointcutPrimitive.CALL));
}
@Test

View File

@ -37,12 +37,13 @@ import org.springframework.lang.Nullable;
import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rod Johnson
@ -54,24 +55,14 @@ public class MethodInvocationProceedingJoinPointTests {
@Test
public void testingBindingWithJoinPoint() {
try {
AbstractAspectJAdvice.currentJoinPoint();
fail("Needs to be bound by interceptor action");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(
AbstractAspectJAdvice::currentJoinPoint);
}
@Test
public void testingBindingWithProceedingJoinPoint() {
try {
AbstractAspectJAdvice.currentJoinPoint();
fail("Needs to be bound by interceptor action");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(
AbstractAspectJAdvice::currentJoinPoint);
}
@Test
@ -148,21 +139,8 @@ public class MethodInvocationProceedingJoinPointTests {
SourceLocation sloc = AbstractAspectJAdvice.currentJoinPoint().getSourceLocation();
assertEquals("Same source location must be returned on subsequent requests", sloc, AbstractAspectJAdvice.currentJoinPoint().getSourceLocation());
assertEquals(TestBean.class, sloc.getWithinType());
try {
sloc.getLine();
fail("Can't get line number");
}
catch (UnsupportedOperationException ex) {
// Expected
}
try {
sloc.getFileName();
fail("Can't get file name");
}
catch (UnsupportedOperationException ex) {
// Expected
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(sloc::getLine);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(sloc::getFileName);
}
});
ITestBean itb = (ITestBean) pf.getProxy();

View File

@ -34,8 +34,8 @@ import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.core.OverridingClassLoader;
import org.springframework.lang.Nullable;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author Dave Syer
@ -112,13 +112,8 @@ public class TrickyAspectJPointcutExpressionTests {
TestService bean = (TestService) factory.getProxy();
assertEquals(0, logAdvice.getCountThrows());
try {
bean.sayHello();
fail("Expected exception");
}
catch (TestException ex) {
assertEquals(message, ex.getMessage());
}
assertThatExceptionOfType(TestException.class).isThrownBy(
bean::sayHello).withMessageContaining(message);
assertEquals(1, logAdvice.getCountThrows());
}

View File

@ -26,6 +26,8 @@ import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.tests.sample.beans.subpkg.DeepBean;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@ -38,10 +40,11 @@ import static org.junit.Assert.assertTrue;
*/
public class TypePatternClassFilterTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testInvalidPattern() {
// should throw - pattern must be recognized as invalid
new TypePatternClassFilter("-");
assertThatIllegalArgumentException().isThrownBy(() ->
new TypePatternClassFilter("-"));
}
@Test
@ -79,14 +82,16 @@ public class TypePatternClassFilterTests {
assertTrue("matches Double",tpcf.matches(Double.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSetTypePatternWithNullArgument() throws Exception {
new TypePatternClassFilter(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new TypePatternClassFilter(null));
}
@Test(expected = IllegalStateException.class)
@Test
public void testInvocationOfMatchesMethodBlowsUpWhenNoTypePatternHasBeenSet() throws Exception {
new TypePatternClassFilter().matches(String.class);
assertThatIllegalStateException().isThrownBy(() ->
new TypePatternClassFilter().matches(String.class));
}
}

View File

@ -58,14 +58,15 @@ import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.ObjectUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Abstract tests for AspectJAdvisorFactory.
@ -86,26 +87,18 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
@Test
public void testRejectsPerCflowAspect() {
try {
assertThatExceptionOfType(AopConfigException.class).isThrownBy(() ->
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new PerCflowAspect(), "someBean"));
fail("Cannot accept cflow");
}
catch (AopConfigException ex) {
assertTrue(ex.getMessage().contains("PERCFLOW"));
}
new SingletonMetadataAwareAspectInstanceFactory(new PerCflowAspect(), "someBean")))
.withMessageContaining("PERCFLOW");
}
@Test
public void testRejectsPerCflowBelowAspect() {
try {
assertThatExceptionOfType(AopConfigException.class).isThrownBy(() ->
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new PerCflowBelowAspect(), "someBean"));
fail("Cannot accept cflowbelow");
}
catch (AopConfigException ex) {
assertTrue(ex.getMessage().contains("PERCFLOWBELOW"));
}
new SingletonMetadataAwareAspectInstanceFactory(new PerCflowBelowAspect(), "someBean")))
.withMessageContaining("PERCFLOWBELOW");
}
@Test
@ -365,12 +358,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
assertFalse(lockable2.locked());
notLockable2.setIntValue(1);
lockable2.lock();
try {
notLockable2.setIntValue(32);
fail();
}
catch (IllegalStateException ex) {
}
assertThatIllegalStateException().isThrownBy(() ->
notLockable2.setIntValue(32));
assertTrue(lockable2.locked());
}
@ -400,13 +389,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
assertTrue("Already locked", lockable.locked());
lockable.lock();
assertTrue("Real target ignores locking", lockable.locked());
try {
lockable.unlock();
fail();
}
catch (UnsupportedOperationException ex) {
// Ok
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
lockable.unlock());
}
@Test
@ -463,13 +447,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
lockable.lock();
assertTrue(lockable.locked());
try {
itb.setName("Else");
fail("Should be locked");
}
catch (IllegalStateException ex) {
// Ok
}
assertThatIllegalStateException().as("Should be locked").isThrownBy(() ->
itb.setName("Else"));
lockable.unlock();
itb.setName("Tony");
}
@ -482,14 +461,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException), "someBean"));
assertEquals("One advice method was found", 1, advisors.size());
ITestBean itb = (ITestBean) createProxy(target, advisors, ITestBean.class);
try {
itb.getAge();
fail();
}
catch (UnsupportedOperationException ex) {
assertSame(expectedException, ex);
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(
itb::getAge);
}
// TODO document this behaviour.
@ -502,14 +475,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException), "someBean"));
assertEquals("One advice method was found", 1, advisors.size());
ITestBean itb = (ITestBean) createProxy(target, advisors, ITestBean.class);
try {
itb.getAge();
fail();
}
catch (UndeclaredThrowableException ex) {
assertSame(expectedException, ex.getCause());
}
assertThatExceptionOfType(UndeclaredThrowableException.class).isThrownBy(
itb::getAge).withCause(expectedException);
}
protected Object createProxy(Object target, List<Advisor> advisors, Class<?>... interfaces) {
@ -555,17 +522,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
assertEquals("", echo.echo(""));
assertEquals(1, afterReturningAspect.successCount);
assertEquals(0, afterReturningAspect.failureCount);
try {
echo.echo(new FileNotFoundException());
fail();
}
catch (FileNotFoundException ex) {
// Ok
}
catch (Exception ex) {
fail();
}
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() ->
echo.echo(new FileNotFoundException()));
assertEquals(1, afterReturningAspect.successCount);
assertEquals(1, afterReturningAspect.failureCount);
assertEquals(afterReturningAspect.failureCount + afterReturningAspect.successCount, afterReturningAspect.afterCount);
@ -581,12 +539,14 @@ public abstract class AbstractAspectJAdvisorFactoryTests {
itb.getAge();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testDeclarePrecedenceNotSupported() {
TestBean target = new TestBean();
assertThatIllegalArgumentException().isThrownBy(() -> {
MetadataAwareAspectInstanceFactory aspectInstanceFactory = new SingletonMetadataAwareAspectInstanceFactory(
new DeclarePrecedenceShouldSucceed(), "someBean");
createProxy(target, getFixture().getAdvisors(aspectInstanceFactory), ITestBean.class);
});
}

View File

@ -30,6 +30,8 @@ import org.springframework.aop.aspectj.AspectJAdviceParameterNameDiscoverer;
import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
/**
@ -39,24 +41,26 @@ import static org.junit.Assert.assertEquals;
*/
public class ArgumentBindingTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testBindingInPointcutUsedByAdvice() {
TestBean tb = new TestBean();
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(tb);
proxyFactory.addAspect(NamedPointcutWithArgs.class);
ITestBean proxiedTestBean = proxyFactory.getProxy();
proxiedTestBean.setName("Supercalifragalisticexpialidocious");
assertThatIllegalArgumentException().isThrownBy(() ->
proxiedTestBean.setName("Supercalifragalisticexpialidocious"));
}
@Test(expected = IllegalStateException.class)
@Test
public void testAnnotationArgumentNameBinding() {
TransactionalBean tb = new TransactionalBean();
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(tb);
proxyFactory.addAspect(PointcutWithAnnotationArgument.class);
ITransactionalBean proxiedTestBean = proxyFactory.getProxy();
proxiedTestBean.doInTransaction();
assertThatIllegalStateException().isThrownBy(
proxiedTestBean::doInTransaction);
}
@Test

View File

@ -25,6 +25,7 @@ import org.springframework.aop.aspectj.AspectJExpressionPointcutTests;
import org.springframework.aop.framework.AopConfigException;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
@ -75,14 +76,16 @@ public class AspectJPointcutAdvisorTests {
TestBean.class.getMethod("getSpouse"), TestBean.class));
}
@Test(expected = AopConfigException.class)
@Test
public void testPerCflowTarget() {
testIllegalInstantiationModel(AbstractAspectJAdvisorFactoryTests.PerCflowAspect.class);
assertThatExceptionOfType(AopConfigException.class).isThrownBy(() ->
testIllegalInstantiationModel(AbstractAspectJAdvisorFactoryTests.PerCflowAspect.class));
}
@Test(expected = AopConfigException.class)
@Test
public void testPerCflowBelowTarget() {
testIllegalInstantiationModel(AbstractAspectJAdvisorFactoryTests.PerCflowBelowAspect.class);
assertThatExceptionOfType(AopConfigException.class).isThrownBy(() ->
testIllegalInstantiationModel(AbstractAspectJAdvisorFactoryTests.PerCflowBelowAspect.class));
}
private void testIllegalInstantiationModel(Class<?> c) throws AopConfigException {

View File

@ -23,6 +23,7 @@ import test.aop.PerTargetAspect;
import org.springframework.aop.Pointcut;
import org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.ExceptionAspect;
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.assertNotSame;
@ -36,9 +37,10 @@ import static org.junit.Assert.assertTrue;
*/
public class AspectMetadataTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testNotAnAspect() {
new AspectMetadata(String.class,"someBean");
assertThatIllegalArgumentException().isThrownBy(() ->
new AspectMetadata(String.class,"someBean"));
}
@Test

View File

@ -28,6 +28,7 @@ import test.aop.PerThisAspect;
import org.springframework.util.SerializationTestUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@ -38,10 +39,11 @@ import static org.junit.Assert.assertTrue;
*/
public class AspectProxyFactoryTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithNonAspect() {
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(new TestBean());
proxyFactory.addAspect(TestBean.class);
assertThatIllegalArgumentException().isThrownBy(() ->
proxyFactory.addAspect(TestBean.class));
}
@Test
@ -74,10 +76,11 @@ public class AspectProxyFactoryTests {
assertEquals(2, proxy1.getAge());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithInstanceWithNonAspect() throws Exception {
AspectJProxyFactory pf = new AspectJProxyFactory();
pf.addAspect(new TestBean());
assertThatIllegalArgumentException().isThrownBy(() ->
pf.addAspect(new TestBean()));
}
@Test
@ -111,10 +114,11 @@ public class AspectProxyFactoryTests {
assertEquals(target.getAge() * multiple, serializedProxy.getAge());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithNonSingletonAspectInstance() throws Exception {
AspectJProxyFactory pf = new AspectJProxyFactory();
pf.addAspect(new PerThisAspect());
assertThatIllegalArgumentException().isThrownBy(() ->
pf.addAspect(new PerThisAspect()));
}
@Test // SPR-13328

View File

@ -23,8 +23,7 @@ import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/**
@ -35,28 +34,20 @@ public class AopNamespaceHandlerPointcutErrorTests {
@Test
public void testDuplicatePointcutConfig() {
try {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
qualifiedResource(getClass(), "pointcutDuplication.xml"));
fail("parsing should have caused a BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
assertTrue(ex.contains(BeanDefinitionParsingException.class));
}
qualifiedResource(getClass(), "pointcutDuplication.xml")))
.satisfies(ex -> ex.contains(BeanDefinitionParsingException.class));
}
@Test
public void testMissingPointcutConfig() {
try {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
qualifiedResource(getClass(), "pointcutMissing.xml"));
fail("parsing should have caused a BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
assertTrue(ex.contains(BeanDefinitionParsingException.class));
}
qualifiedResource(getClass(), "pointcutMissing.xml")))
.satisfies(ex -> ex.contains(BeanDefinitionParsingException.class));
}
}

View File

@ -26,6 +26,7 @@ import org.springframework.aop.SpringProxy;
import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean;
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;
@ -125,11 +126,12 @@ public class AopProxyUtilsTests {
assertEquals(Comparable.class, userInterfaces[1]);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testProxiedUserInterfacesWithNoInterface() {
Object proxy = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[0],
(proxy1, method, args) -> null);
AopProxyUtils.proxiedUserInterfaces(proxy);
assertThatIllegalArgumentException().isThrownBy(() ->
AopProxyUtils.proxiedUserInterfaces(proxy));
}
}

View File

@ -42,6 +42,7 @@ import org.springframework.tests.sample.beans.IOther;
import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
@ -49,7 +50,6 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Also tests AdvisedSupport and ProxyCreatorSupport superclasses.
@ -277,13 +277,9 @@ public class ProxyFactoryTests {
assertTrue(config.getAdvisors().length == oldCount);
try {
// Existing reference will fail
ts.getTimeStamp();
fail("Existing object won't implement this interface any more");
}
catch (RuntimeException ex) {
}
assertThatExceptionOfType(RuntimeException.class)
.as("Existing object won't implement this interface any more")
.isThrownBy(ts::getTimeStamp); // Existing reference will fail
assertFalse("Should no longer implement TimeStamped",
config.getProxy() instanceof TimeStamped);

View File

@ -28,8 +28,9 @@ import org.junit.Test;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.tests.aop.advice.MethodCounter;
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.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -39,10 +40,11 @@ import static org.mockito.Mockito.mock;
*/
public class ThrowsAdviceInterceptorTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testNoHandlerMethods() {
// should require one handler method at least
new ThrowsAdviceInterceptor(new Object());
assertThatIllegalArgumentException().isThrownBy(() ->
new ThrowsAdviceInterceptor(new Object()));
}
@Test
@ -64,13 +66,9 @@ public class ThrowsAdviceInterceptorTests {
Exception ex = new Exception();
MethodInvocation mi = mock(MethodInvocation.class);
given(mi.proceed()).willThrow(ex);
try {
ti.invoke(mi);
fail();
}
catch (Exception caught) {
assertEquals(ex, caught);
}
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
ti.invoke(mi))
.isSameAs(ex);
assertEquals(0, th.getCalls());
}
@ -83,13 +81,9 @@ public class ThrowsAdviceInterceptorTests {
given(mi.getMethod()).willReturn(Object.class.getMethod("hashCode"));
given(mi.getThis()).willReturn(new Object());
given(mi.proceed()).willThrow(ex);
try {
ti.invoke(mi);
fail();
}
catch (Exception caught) {
assertEquals(ex, caught);
}
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() ->
ti.invoke(mi))
.isSameAs(ex);
assertEquals(1, th.getCalls());
assertEquals(1, th.getCalls("ioException"));
}
@ -102,13 +96,9 @@ public class ThrowsAdviceInterceptorTests {
ConnectException ex = new ConnectException("");
MethodInvocation mi = mock(MethodInvocation.class);
given(mi.proceed()).willThrow(ex);
try {
ti.invoke(mi);
fail();
}
catch (Exception caught) {
assertEquals(ex, caught);
}
assertThatExceptionOfType(ConnectException.class).isThrownBy(() ->
ti.invoke(mi))
.isSameAs(ex);
assertEquals(1, th.getCalls());
assertEquals(1, th.getCalls("remoteException"));
}
@ -131,13 +121,9 @@ public class ThrowsAdviceInterceptorTests {
ConnectException ex = new ConnectException("");
MethodInvocation mi = mock(MethodInvocation.class);
given(mi.proceed()).willThrow(ex);
try {
ti.invoke(mi);
fail();
}
catch (Throwable caught) {
assertEquals(t, caught);
}
assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
ti.invoke(mi))
.isSameAs(t);
assertEquals(1, th.getCalls());
assertEquals(1, th.getCalls("remoteException"));
}

View File

@ -20,7 +20,7 @@ import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.junit.Test;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@ -36,52 +36,60 @@ import static org.mockito.Mockito.verify;
*/
public class CustomizableTraceInterceptorTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testSetEmptyEnterMessage() {
// Must not be able to set empty enter message
new CustomizableTraceInterceptor().setEnterMessage("");
assertThatIllegalArgumentException().isThrownBy(() ->
new CustomizableTraceInterceptor().setEnterMessage(""));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSetEnterMessageWithReturnValuePlaceholder() {
// Must not be able to set enter message with return value placeholder
new CustomizableTraceInterceptor().setEnterMessage(CustomizableTraceInterceptor.PLACEHOLDER_RETURN_VALUE);
assertThatIllegalArgumentException().isThrownBy(() ->
new CustomizableTraceInterceptor().setEnterMessage(CustomizableTraceInterceptor.PLACEHOLDER_RETURN_VALUE));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSetEnterMessageWithExceptionPlaceholder() {
// Must not be able to set enter message with exception placeholder
new CustomizableTraceInterceptor().setEnterMessage(CustomizableTraceInterceptor.PLACEHOLDER_EXCEPTION);
assertThatIllegalArgumentException().isThrownBy(() ->
new CustomizableTraceInterceptor().setEnterMessage(CustomizableTraceInterceptor.PLACEHOLDER_EXCEPTION));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSetEnterMessageWithInvocationTimePlaceholder() {
// Must not be able to set enter message with invocation time placeholder
new CustomizableTraceInterceptor().setEnterMessage(CustomizableTraceInterceptor.PLACEHOLDER_INVOCATION_TIME);
assertThatIllegalArgumentException().isThrownBy(() ->
new CustomizableTraceInterceptor().setEnterMessage(CustomizableTraceInterceptor.PLACEHOLDER_INVOCATION_TIME));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSetEmptyExitMessage() {
// Must not be able to set empty exit message
new CustomizableTraceInterceptor().setExitMessage("");
assertThatIllegalArgumentException().isThrownBy(() ->
new CustomizableTraceInterceptor().setExitMessage(""));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSetExitMessageWithExceptionPlaceholder() {
// Must not be able to set exit message with exception placeholder
new CustomizableTraceInterceptor().setExitMessage(CustomizableTraceInterceptor.PLACEHOLDER_EXCEPTION);
assertThatIllegalArgumentException().isThrownBy(() ->
new CustomizableTraceInterceptor().setExitMessage(CustomizableTraceInterceptor.PLACEHOLDER_EXCEPTION));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSetEmptyExceptionMessage() {
// Must not be able to set empty exception message
new CustomizableTraceInterceptor().setExceptionMessage("");
assertThatIllegalArgumentException().isThrownBy(() ->
new CustomizableTraceInterceptor().setExceptionMessage(""));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSetExceptionMethodWithReturnValuePlaceholder() {
// Must not be able to set exception message with return value placeholder
new CustomizableTraceInterceptor().setExceptionMessage(CustomizableTraceInterceptor.PLACEHOLDER_RETURN_VALUE);
assertThatIllegalArgumentException().isThrownBy(() ->
new CustomizableTraceInterceptor().setExceptionMessage(CustomizableTraceInterceptor.PLACEHOLDER_RETURN_VALUE));
}
@Test
@ -114,12 +122,8 @@ public class CustomizableTraceInterceptorTests {
given(log.isTraceEnabled()).willReturn(true);
CustomizableTraceInterceptor interceptor = new StubCustomizableTraceInterceptor(log);
try {
interceptor.invoke(methodInvocation);
fail("Must have propagated the IllegalArgumentException.");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
interceptor.invoke(methodInvocation));
verify(log).trace(anyString());
verify(log).trace(anyString(), eq(exception));

View File

@ -20,8 +20,8 @@ import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@ -64,12 +64,8 @@ public class DebugInterceptorTests {
given(log.isTraceEnabled()).willReturn(true);
DebugInterceptor interceptor = new StubDebugInterceptor(log);
try {
interceptor.invoke(methodInvocation);
fail("Must have propagated the IllegalArgumentException.");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
interceptor.invoke(methodInvocation));
checkCallCountTotal(interceptor);
verify(log).trace(anyString());

View File

@ -23,9 +23,9 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -69,12 +69,8 @@ public class JamonPerformanceMonitorInterceptorTests {
given(mi.getMethod()).willReturn(String.class.getMethod("toString"));
given(mi.proceed()).willThrow(new IllegalArgumentException());
try {
interceptor.invokeUnderTrace(mi, log);
fail("Must have propagated the IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
interceptor.invokeUnderTrace(mi, log));
assertEquals("Monitors must exist for the method invocation and 2 exceptions",
3, MonitorFactory.getNumRows());

View File

@ -20,8 +20,8 @@ import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -70,12 +70,8 @@ public class PerformanceMonitorInterceptorTests {
Log log = mock(Log.class);
PerformanceMonitorInterceptor interceptor = new PerformanceMonitorInterceptor(true);
try {
interceptor.invokeUnderTrace(mi, log);
fail("Must have propagated the IllegalArgumentException.");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
interceptor.invokeUnderTrace(mi, log));
verify(log).trace(anyString());
}

View File

@ -20,7 +20,7 @@ import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.junit.Test;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@ -61,13 +61,8 @@ public class SimpleTraceInterceptorTests {
Log log = mock(Log.class);
final SimpleTraceInterceptor interceptor = new SimpleTraceInterceptor(true);
try {
interceptor.invokeUnderTrace(mi, log);
fail("Must have propagated the IllegalArgumentException.");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
interceptor.invokeUnderTrace(mi, log));
verify(log).trace(anyString());
verify(log).trace(anyString(), eq(exception));

View File

@ -20,6 +20,7 @@ import org.junit.Test;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@ -33,24 +34,28 @@ public class DefaultScopedObjectTests {
private static final String GOOD_BEAN_NAME = "foo";
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWithNullBeanFactory() throws Exception {
new DefaultScopedObject(null, GOOD_BEAN_NAME);
assertThatIllegalArgumentException().isThrownBy(() ->
new DefaultScopedObject(null, GOOD_BEAN_NAME));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWithNullTargetBeanName() throws Exception {
testBadTargetBeanName(null);
assertThatIllegalArgumentException().isThrownBy(() ->
testBadTargetBeanName(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWithEmptyTargetBeanName() throws Exception {
testBadTargetBeanName("");
assertThatIllegalArgumentException().isThrownBy(() ->
testBadTargetBeanName(""));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWithJustWhitespacedTargetBeanName() throws Exception {
testBadTargetBeanName(" ");
assertThatIllegalArgumentException().isThrownBy(() ->
testBadTargetBeanName(" "));
}
private static void testBadTargetBeanName(final String badTargetBeanName) {

View File

@ -34,6 +34,7 @@ import org.springframework.tests.sample.beans.SerializablePerson;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.SerializationTestUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
@ -49,10 +50,11 @@ import static org.mockito.Mockito.mock;
*/
public class DelegatingIntroductionInterceptorTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testNullTarget() throws Exception {
// Shouldn't accept null target
new DelegatingIntroductionInterceptor(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new DelegatingIntroductionInterceptor(null));
}
@Test

View File

@ -31,9 +31,8 @@ import org.springframework.tests.sample.beans.SerializablePerson;
import org.springframework.tests.sample.beans.SideEffectBean;
import org.springframework.util.SerializationTestUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/**
@ -110,19 +109,11 @@ public class HotSwappableTargetSourceTests {
@Test
public void testRejectsSwapToNull() {
HotSwappableTargetSource swapper = (HotSwappableTargetSource) beanFactory.getBean("swapper");
IllegalArgumentException aopex = null;
try {
swapper.swap(null);
fail("Shouldn't be able to swap to invalid value");
}
catch (IllegalArgumentException ex) {
// Ok
aopex = ex;
}
assertThatIllegalArgumentException().as("Shouldn't be able to swap to invalid value").isThrownBy(() ->
swapper.swap(null))
.withMessageContaining("null");
// It shouldn't be corrupted, it should still work
testBasicFunctionality();
assertTrue(aopex.getMessage().contains("null"));
}
@Test

View File

@ -26,7 +26,6 @@ import org.springframework.tests.sample.beans.SideEffectBean;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/**
@ -154,12 +153,7 @@ public class ThreadLocalTargetSourceTests {
source.destroy();
// try second time
try {
source.getTarget();
}
catch (NullPointerException ex) {
fail("Should not throw NPE");
}
source.getTarget(); // Should not throw NPE
}
}

View File

@ -43,7 +43,6 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
/**
* Unit tests for {@link AnnotationAsyncExecutionAspect}.
@ -176,18 +175,12 @@ public class AnnotationAsyncExecutionAspectTests {
try {
assertFalse("Handler should not have been called", exceptionHandler.isCalled());
ClassWithException obj = new ClassWithException();
try {
obj.failWithVoid();
exceptionHandler.await(3000);
exceptionHandler.assertCalledWith(m, UnsupportedOperationException.class);
}
catch (Exception ex) {
fail("No unexpected exception should have been received but got " + ex.getMessage());
}
}
finally {
AnnotationAsyncExecutionAspect.aspectOf().setExceptionHandler(defaultExceptionHandler);
}
}
@ -215,7 +208,7 @@ public class AnnotationAsyncExecutionAspectTests {
wait(WAIT_TIME);
}
catch (InterruptedException ex) {
fail("Didn't finish the async job in " + WAIT_TIME + " milliseconds");
throw new AssertionError("Didn't finish the async job in " + WAIT_TIME + " milliseconds");
}
}
}

View File

@ -30,8 +30,9 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.tests.transaction.CallCountingTransactionManager;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author Stephane Nicoll
@ -59,13 +60,9 @@ public class JtaTransactionAspectsTests {
public void matchingRollbackOnApplied() throws Throwable {
assertEquals(0, this.txManager.begun);
InterruptedException test = new InterruptedException();
try {
new JtaAnnotationPublicAnnotatedMember().echo(test);
fail("Should have thrown an exception");
}
catch (Throwable throwable) {
assertEquals("wrong exception", test, throwable);
}
assertThatExceptionOfType(InterruptedException.class).isThrownBy(() ->
new JtaAnnotationPublicAnnotatedMember().echo(test))
.isSameAs(test);
assertEquals(1, this.txManager.rollbacks);
assertEquals(0, this.txManager.commits);
}
@ -74,13 +71,9 @@ public class JtaTransactionAspectsTests {
public void nonMatchingRollbackOnApplied() throws Throwable {
assertEquals(0, this.txManager.begun);
IOException test = new IOException();
try {
new JtaAnnotationPublicAnnotatedMember().echo(test);
fail("Should have thrown an exception");
}
catch (Throwable throwable) {
assertEquals("wrong exception", test, throwable);
}
assertThatIOException().isThrownBy(() ->
new JtaAnnotationPublicAnnotatedMember().echo(test))
.isSameAs(test);
assertEquals(1, this.txManager.commits);
assertEquals(0, this.txManager.rollbacks);
}

View File

@ -21,9 +21,8 @@ import org.junit.Test;
import org.springframework.tests.transaction.CallCountingTransactionManager;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
/**
* @author Rod Johnson
@ -104,50 +103,34 @@ public class TransactionAspectTests {
@Test
public void defaultCommitOnAnnotatedClass() throws Throwable {
final Exception ex = new Exception();
try {
testRollback(() -> annotationOnlyOnClassWithNoInterface.echo(ex), false);
fail("Should have thrown Exception");
}
catch (Exception ex2) {
assertSame(ex, ex2);
}
Exception ex = new Exception();
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
testRollback(() -> annotationOnlyOnClassWithNoInterface.echo(ex), false))
.isSameAs(ex);
}
@Test
public void defaultRollbackOnAnnotatedClass() throws Throwable {
final RuntimeException ex = new RuntimeException();
try {
testRollback(() -> annotationOnlyOnClassWithNoInterface.echo(ex), true);
fail("Should have thrown RuntimeException");
}
catch (RuntimeException ex2) {
assertSame(ex, ex2);
}
RuntimeException ex = new RuntimeException();
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
testRollback(() -> annotationOnlyOnClassWithNoInterface.echo(ex), true))
.isSameAs(ex);
}
@Test
public void defaultCommitOnSubclassOfAnnotatedClass() throws Throwable {
final Exception ex = new Exception();
try {
testRollback(() -> new SubclassOfClassWithTransactionalAnnotation().echo(ex), false);
fail("Should have thrown Exception");
}
catch (Exception ex2) {
assertSame(ex, ex2);
}
Exception ex = new Exception();
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
testRollback(() -> new SubclassOfClassWithTransactionalAnnotation().echo(ex), false))
.isSameAs(ex);
}
@Test
public void defaultCommitOnSubclassOfClassWithTransactionalMethodAnnotated() throws Throwable {
final Exception ex = new Exception();
try {
testRollback(() -> new SubclassOfClassWithTransactionalMethodAnnotation().echo(ex), false);
fail("Should have thrown Exception");
}
catch (Exception ex2) {
assertSame(ex, ex2);
}
Exception ex = new Exception();
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
testRollback(() -> new SubclassOfClassWithTransactionalMethodAnnotation().echo(ex), false))
.isSameAs(ex);
}
@Test
@ -180,19 +163,10 @@ public class TransactionAspectTests {
protected void testNotTransactional(TransactionOperationCallback toc, Throwable expected) throws Throwable {
txManager.clear();
assertEquals(0, txManager.begun);
try {
toc.performTransactionalOperation();
}
catch (Throwable ex) {
if (expected == null) {
fail("Expected " + expected);
}
assertSame(expected, ex);
}
finally {
assertThatExceptionOfType(Throwable.class).isThrownBy(
toc::performTransactionalOperation).isSameAs(expected);
assertEquals(0, txManager.begun);
}
}
private interface TransactionOperationCallback {

View File

@ -58,6 +58,7 @@ import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.is;
@ -69,7 +70,6 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Shared tests for property accessors.
@ -90,13 +90,8 @@ public abstract class AbstractPropertyAccessorTests {
@Test
public void createWithNullTarget() {
try {
createAccessor(null);
fail("Must throw an exception when constructed with null object");
}
catch (IllegalArgumentException ex) {
// expected
}
assertThatIllegalArgumentException().isThrownBy(() ->
createAccessor(null));
}
@Test
@ -240,15 +235,12 @@ public abstract class AbstractPropertyAccessorTests {
Person target = createPerson("John", "London", "UK");
target.address = null;
AbstractPropertyAccessor accessor = createAccessor(target);
try {
accessor.getPropertyValue("address.country.name");
fail("Should have failed to get value with null intermediate path");
}
catch (NullValueInNestedPathException e) {
assertEquals("address", e.getPropertyName());
assertEquals(Person.class, e.getBeanClass());
}
assertThatExceptionOfType(NullValueInNestedPathException.class).isThrownBy(() ->
accessor.getPropertyValue("address.country.name"))
.satisfies(ex -> {
assertThat(ex.getPropertyName()).isEqualTo("address");
assertThat(ex.getBeanClass()).isEqualTo(Person.class);
});
}
@Test
@ -275,15 +267,12 @@ public abstract class AbstractPropertyAccessorTests {
public void getUnknownProperty() {
Simple target = new Simple("John", 2);
AbstractPropertyAccessor accessor = createAccessor(target);
try {
accessor.getPropertyValue("foo");
fail("Should have failed to get an unknown property.");
}
catch (NotReadablePropertyException e) {
assertEquals(Simple.class, e.getBeanClass());
assertEquals("foo", e.getPropertyName());
}
assertThatExceptionOfType(NotReadablePropertyException.class).isThrownBy(() ->
accessor.getPropertyValue("foo"))
.satisfies(ex -> {
assertThat(ex.getBeanClass()).isEqualTo(Simple.class);
assertThat(ex.getPropertyName()).isEqualTo("foo");
});
}
@Test
@ -398,31 +387,22 @@ public abstract class AbstractPropertyAccessorTests {
Person target = createPerson("John", "Paris", "FR");
target.address.country = null;
AbstractPropertyAccessor accessor = createAccessor(target);
try {
accessor.setPropertyValue("address.country.name", "UK");
fail("Should have failed to set value with intermediate null value");
}
catch (NullValueInNestedPathException e) {
assertEquals("address.country", e.getPropertyName());
assertEquals(Person.class, e.getBeanClass());
}
assertThat(target.address.country, is(nullValue())); // Not touched
assertThatExceptionOfType(NullValueInNestedPathException.class).isThrownBy(() ->
accessor.setPropertyValue("address.country.name", "UK"))
.satisfies(ex -> {
assertThat(ex.getPropertyName()).isEqualTo("address.country");
assertThat(ex.getBeanClass()).isEqualTo(Person.class);
});
assertThat(target.address.country).isNull(); // Not touched
}
@Test
public void setAnotherPropertyIntermediatePropertyIsNull() throws Exception {
ITestBean target = new TestBean("rod", 31);
AbstractPropertyAccessor accessor = createAccessor(target);
try {
accessor.setPropertyValue("spouse.age", new Integer(31));
fail("Shouldn't have succeeded with null path");
}
catch (NullValueInNestedPathException ex) {
// expected
assertTrue("it was the spouse property that was null, not " + ex.getPropertyName(),
ex.getPropertyName().equals("spouse"));
}
assertThatExceptionOfType(NullValueInNestedPathException.class).isThrownBy(() ->
accessor.setPropertyValue("spouse.age", new Integer(31)))
.satisfies(ex -> assertThat(ex.getPropertyName()).isEqualTo("spouse"));
}
@Test
@ -481,7 +461,6 @@ public abstract class AbstractPropertyAccessorTests {
String name = "Tony";
target.setAge(age);
target.setName(name);
try {
AbstractPropertyAccessor accessor = createAccessor(target);
assertTrue("age is OK", target.getAge() == age);
assertTrue("name is OK", name.equals(target.getName()));
@ -490,10 +469,6 @@ public abstract class AbstractPropertyAccessorTests {
assertTrue("age is OK", target.getAge() == age);
assertTrue("name is OK", name.equals(target.getName()));
}
catch (BeansException ex) {
fail("Shouldn't throw exception when everything is valid");
}
}
@Test
@ -502,7 +477,6 @@ public abstract class AbstractPropertyAccessorTests {
String newName = "tony";
int newAge = 65;
String newTouchy = "valid";
try {
AbstractPropertyAccessor accessor = createAccessor(target);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("age", newAge));
@ -513,10 +487,6 @@ public abstract class AbstractPropertyAccessorTests {
assertTrue("Touchy property should have changed", target.getTouchy().equals(newTouchy));
assertTrue("Age property should have changed", target.getAge() == newAge);
}
catch (BeansException ex) {
fail("Shouldn't throw exception when everything is valid");
}
}
@Test
public void setIndividualValidPropertyValues() {
@ -524,7 +494,6 @@ public abstract class AbstractPropertyAccessorTests {
String newName = "tony";
int newAge = 65;
String newTouchy = "valid";
try {
AbstractPropertyAccessor accessor = createAccessor(target);
accessor.setPropertyValue("age", new Integer(newAge));
accessor.setPropertyValue(new PropertyValue("name", newName));
@ -533,26 +502,17 @@ public abstract class AbstractPropertyAccessorTests {
assertTrue("Touchy property should have changed", target.getTouchy().equals(newTouchy));
assertTrue("Age property should have changed", target.getAge() == newAge);
}
catch (BeansException ex) {
fail("Shouldn't throw exception when everything is valid");
}
}
@Test
public void setPropertyIsReflectedImmediately() {
TestBean target = new TestBean();
int newAge = 33;
try {
AbstractPropertyAccessor accessor = createAccessor(target);
target.setAge(newAge);
Object bwAge = accessor.getPropertyValue("age");
assertTrue("Age is an integer", bwAge instanceof Integer);
assertTrue("Bean wrapper must pick up changes", (int) bwAge == newAge);
}
catch (Exception ex) {
fail("Shouldn't throw exception when everything is valid");
}
}
@Test
public void setPropertyToNull() {
@ -645,8 +605,6 @@ public abstract class AbstractPropertyAccessorTests {
public void setNumberProperties() {
NumberTestBean target = new NumberTestBean();
AbstractPropertyAccessor accessor = createAccessor(target);
try {
accessor.setPropertyValue("short2", "2");
accessor.setPropertyValue("int2", "8");
accessor.setPropertyValue("long2", "6");
@ -654,11 +612,6 @@ public abstract class AbstractPropertyAccessorTests {
accessor.setPropertyValue("float2", "8.1");
accessor.setPropertyValue("double2", "6.1");
accessor.setPropertyValue("bigDecimal", "4.0");
}
catch (BeansException ex) {
fail("Should not throw BeansException: " + ex.getMessage());
}
assertTrue("Correct short2 value", new Short("2").equals(accessor.getPropertyValue("short2")));
assertTrue("Correct short2 value", new Short("2").equals(target.getShort2()));
assertTrue("Correct int2 value", new Integer("8").equals(accessor.getPropertyValue("int2")));
@ -679,8 +632,6 @@ public abstract class AbstractPropertyAccessorTests {
public void setNumberPropertiesWithCoercion() {
NumberTestBean target = new NumberTestBean();
AbstractPropertyAccessor accessor = createAccessor(target);
try {
accessor.setPropertyValue("short2", new Integer(2));
accessor.setPropertyValue("int2", new Long(8));
accessor.setPropertyValue("long2", new BigInteger("6"));
@ -688,11 +639,6 @@ public abstract class AbstractPropertyAccessorTests {
accessor.setPropertyValue("float2", new Double(8.1));
accessor.setPropertyValue("double2", new BigDecimal(6.1));
accessor.setPropertyValue("bigDecimal", new Float(4.0));
}
catch (BeansException ex) {
fail("Should not throw BeansException: " + ex.getMessage());
}
assertTrue("Correct short2 value", new Short("2").equals(accessor.getPropertyValue("short2")));
assertTrue("Correct short2 value", new Short("2").equals(target.getShort2()));
assertTrue("Correct int2 value", new Integer("8").equals(accessor.getPropertyValue("int2")));
@ -770,13 +716,8 @@ public abstract class AbstractPropertyAccessorTests {
accessor.setPropertyValue("autowire", " BY_TYPE ");
assertEquals(Autowire.BY_TYPE, target.getAutowire());
try {
accessor.setPropertyValue("autowire", "NHERITED");
fail("Should have thrown TypeMismatchException");
}
catch (TypeMismatchException ex) {
// expected
}
assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() ->
accessor.setPropertyValue("autowire", "NHERITED"));
}
@Test
@ -1392,24 +1333,19 @@ public abstract class AbstractPropertyAccessorTests {
}
});
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("map[key1]", "rod");
pvs.add("map[key2]", "rob");
accessor.setPropertyValues(pvs);
MutablePropertyValues goodValues = new MutablePropertyValues();
goodValues.add("map[key1]", "rod");
goodValues.add("map[key2]", "rob");
accessor.setPropertyValues(goodValues);
assertEquals("rod", ((TestBean) target.getMap().get("key1")).getName());
assertEquals("rob", ((TestBean) target.getMap().get("key2")).getName());
pvs = new MutablePropertyValues();
pvs.add("map[key1]", "rod");
pvs.add("map[key2]", "");
try {
accessor.setPropertyValues(pvs);
fail("Should have thrown TypeMismatchException");
}
catch (PropertyBatchUpdateException ex) {
PropertyAccessException pae = ex.getPropertyAccessException("map[key2]");
assertTrue(pae instanceof TypeMismatchException);
}
MutablePropertyValues badValues = new MutablePropertyValues();
badValues.add("map[key1]", "rod");
badValues.add("map[key2]", "");
assertThatExceptionOfType(PropertyBatchUpdateException.class).isThrownBy(() ->
accessor.setPropertyValues(badValues))
.satisfies(ex -> assertThat(ex.getPropertyAccessException("map[key2]")).isInstanceOf(TypeMismatchException.class));
}
@Test
@ -1480,48 +1416,35 @@ public abstract class AbstractPropertyAccessorTests {
public void setUnknownProperty() {
Simple target = new Simple("John", 2);
AbstractPropertyAccessor accessor = createAccessor(target);
try {
accessor.setPropertyValue("name1", "value");
fail("Should have failed to set an unknown property.");
}
catch (NotWritablePropertyException e) {
assertEquals(Simple.class, e.getBeanClass());
assertEquals("name1", e.getPropertyName());
assertEquals("Invalid number of possible matches", 1, e.getPossibleMatches().length);
assertEquals("name", e.getPossibleMatches()[0]);
}
assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() ->
accessor.setPropertyValue("name1", "value"))
.satisfies(ex -> {
assertThat(ex.getBeanClass()).isEqualTo(Simple.class);
assertThat(ex.getPropertyName()).isEqualTo("name1");
assertThat(ex.getPossibleMatches()).containsExactly("name");
});
}
@Test
public void setUnknownPropertyWithPossibleMatches() {
Simple target = new Simple("John", 2);
AbstractPropertyAccessor accessor = createAccessor(target);
try {
accessor.setPropertyValue("foo", "value");
fail("Should have failed to set an unknown property.");
}
catch (NotWritablePropertyException e) {
assertEquals(Simple.class, e.getBeanClass());
assertEquals("foo", e.getPropertyName());
}
assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() ->
accessor.setPropertyValue("foo", "value"))
.satisfies(ex -> {
assertThat(ex.getBeanClass()).isEqualTo(Simple.class);
assertThat(ex.getPropertyName()).isEqualTo("foo");
});
}
@Test
public void setUnknownOptionalProperty() {
Simple target = new Simple("John", 2);
AbstractPropertyAccessor accessor = createAccessor(target);
try {
PropertyValue value = new PropertyValue("foo", "value");
value.setOptional(true);
accessor.setPropertyValue(value);
}
catch (NotWritablePropertyException e) {
fail("Should not have failed to set an unknown optional property.");
}
}
@Test
public void setPropertyInProtectedBaseBean() {
@ -1535,30 +1458,17 @@ public abstract class AbstractPropertyAccessorTests {
@Test
public void setPropertyTypeMismatch() {
TestBean target = new TestBean();
try {
AbstractPropertyAccessor accessor = createAccessor(target);
accessor.setPropertyValue("age", "foobar");
fail("Should throw exception on type mismatch");
}
catch (TypeMismatchException ex) {
// expected
}
assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() ->
accessor.setPropertyValue("age", "foobar"));
}
@Test
public void setEmptyValueForPrimitiveProperty() {
TestBean target = new TestBean();
try {
AbstractPropertyAccessor accessor = createAccessor(target);
accessor.setPropertyValue("age", "");
fail("Should throw exception on type mismatch");
}
catch (TypeMismatchException ex) {
// expected
}
catch (Exception ex) {
fail("Shouldn't throw exception other than Type mismatch");
}
assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() ->
accessor.setPropertyValue("age", ""));
}
@Test
@ -1580,14 +1490,8 @@ public abstract class AbstractPropertyAccessorTests {
AbstractPropertyAccessor accessor = createAccessor(target);
accessor.setPropertyValues(pvs, true);
assertTrue("Set valid and ignored invalid", target.getName().equals("rod"));
try {
// Don't ignore: should fail
accessor.setPropertyValues(pvs, false);
fail("Shouldn't have ignored invalid updates");
}
catch (NotWritablePropertyException ex) {
// OK: but which exception??
}
assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() ->
accessor.setPropertyValues(pvs, false)); // Don't ignore: should fail
}
@Test

View File

@ -33,6 +33,8 @@ import org.springframework.tests.sample.beans.DerivedTestBean;
import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@ -49,14 +51,16 @@ import static org.junit.Assert.assertTrue;
*/
public class BeanUtilsTests {
@Test(expected = FatalBeanException.class)
@Test
public void testInstantiateClassGivenInterface() {
BeanUtils.instantiateClass(List.class);
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() ->
BeanUtils.instantiateClass(List.class));
}
@Test(expected = FatalBeanException.class)
@Test
public void testInstantiateClassGivenClassWithoutDefaultConstructor() {
BeanUtils.instantiateClass(CustomDateEditor.class);
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() ->
BeanUtils.instantiateClass(CustomDateEditor.class));
}
@Test // gh-22531
@ -78,10 +82,11 @@ public class BeanUtilsTests {
assertEquals("foo", bean.getValue());
}
@Test(expected = BeanInstantiationException.class) // gh-22531
@Test // gh-22531
public void testInstantiateClassWithMoreArgsThanParameters() throws NoSuchMethodException {
Constructor<BeanWithPrimitiveTypes> ctor = BeanWithPrimitiveTypes.class.getDeclaredConstructor(int.class, boolean.class, String.class);
BeanUtils.instantiateClass(ctor, null, null, "foo", null);
assertThatExceptionOfType(BeanInstantiationException.class).isThrownBy(() ->
BeanUtils.instantiateClass(ctor, null, null, "foo", null));
}
@Test
@ -221,14 +226,16 @@ public class BeanUtilsTests {
assertSignatureEquals(desiredMethod, "doSomething()");
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testResolveInvalidSignatureEndParen() {
BeanUtils.resolveSignature("doSomething(", MethodSignatureBean.class);
assertThatIllegalArgumentException().isThrownBy(() ->
BeanUtils.resolveSignature("doSomething(", MethodSignatureBean.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testResolveInvalidSignatureStartParen() {
BeanUtils.resolveSignature("doSomething)", MethodSignatureBean.class);
assertThatIllegalArgumentException().isThrownBy(() ->
BeanUtils.resolveSignature("doSomething)", MethodSignatureBean.class));
}
@Test

View File

@ -22,13 +22,12 @@ import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Keith Donald
@ -58,9 +57,10 @@ public class BeanWrapperAutoGrowingTests {
assertEquals("test", bean.getNested().getProp());
}
@Test(expected = NullValueInNestedPathException.class)
@Test
public void getPropertyValueNullValueInNestedPathNoDefaultConstructor() {
wrapper.getPropertyValue("nestedNoConstructor.prop");
assertThatExceptionOfType(NullValueInNestedPathException.class).isThrownBy(() ->
wrapper.getPropertyValue("nestedNoConstructor.prop"));
}
@Test
@ -129,14 +129,9 @@ public class BeanWrapperAutoGrowingTests {
@Test
public void getPropertyValueAutoGrowListFailsAgainstLimit() {
wrapper.setAutoGrowCollectionLimit(2);
try {
assertNotNull(wrapper.getPropertyValue("list[4]"));
fail("Should have thrown InvalidPropertyException");
}
catch (InvalidPropertyException ex) {
// expected
assertTrue(ex.getRootCause() instanceof IndexOutOfBoundsException);
}
assertThatExceptionOfType(InvalidPropertyException.class).isThrownBy(() ->
assertNotNull(wrapper.getPropertyValue("list[4]")))
.withRootCauseInstanceOf(IndexOutOfBoundsException.class);
}
@Test
@ -146,9 +141,10 @@ public class BeanWrapperAutoGrowingTests {
assertThat(bean.getMultiList().get(0).get(0), instanceOf(Bean.class));
}
@Test(expected = InvalidPropertyException.class)
@Test
public void getPropertyValueAutoGrowListNotParameterized() {
wrapper.getPropertyValue("listNotParameterized[0]");
assertThatExceptionOfType(InvalidPropertyException.class).isThrownBy(() ->
wrapper.getPropertyValue("listNotParameterized[0]"));
}
@Test

View File

@ -39,9 +39,9 @@ import org.springframework.tests.sample.beans.GenericIntegerBean;
import org.springframework.tests.sample.beans.GenericSetOfIntegerBean;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@ -81,13 +81,9 @@ public class BeanWrapperGenericsTests {
BeanWrapper bw = new BeanWrapperImpl(gb);
Set<TestBean> input = new HashSet<>();
input.add(new TestBean());
try {
bw.setPropertyValue("integerSet", input);
fail("Should have thrown TypeMismatchException");
}
catch (TypeMismatchException ex) {
assertTrue(ex.getMessage().contains("java.lang.Integer"));
}
assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() ->
bw.setPropertyValue("integerSet", input))
.withMessageContaining("java.lang.Integer");
}
@Test

View File

@ -24,12 +24,12 @@ import org.junit.Test;
import org.springframework.tests.sample.beans.TestBean;
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.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Specific {@link BeanWrapperImpl} tests.
@ -82,38 +82,30 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests {
TestBean target = new TestBean();
String newName = "tony";
String invalidTouchy = ".valid";
try {
BeanWrapper accessor = createAccessor(target);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("age", "foobar"));
pvs.addPropertyValue(new PropertyValue("name", newName));
pvs.addPropertyValue(new PropertyValue("touchy", invalidTouchy));
accessor.setPropertyValues(pvs);
fail("Should throw exception when everything is valid");
}
catch (PropertyBatchUpdateException ex) {
assertTrue("Must contain 2 exceptions", ex.getExceptionCount() == 2);
assertThatExceptionOfType(PropertyBatchUpdateException.class).isThrownBy(() ->
accessor.setPropertyValues(pvs))
.satisfies(ex -> {
assertThat(ex.getExceptionCount()).isEqualTo(2);
assertThat(ex.getPropertyAccessException("touchy").getPropertyChangeEvent()
.getNewValue()).isEqualTo(invalidTouchy);
});
// Test validly set property matches
assertTrue("Valid set property must stick", target.getName().equals(newName));
assertTrue("Invalid set property must retain old value", target.getAge() == 0);
assertTrue("New value of dodgy setter must be available through exception",
ex.getPropertyAccessException("touchy").getPropertyChangeEvent().getNewValue().equals(invalidTouchy));
}
}
@Test
public void checkNotWritablePropertyHoldPossibleMatches() {
TestBean target = new TestBean();
try {
BeanWrapper accessor = createAccessor(target);
accessor.setPropertyValue("ag", "foobar");
fail("Should throw exception on invalid property");
}
catch (NotWritablePropertyException ex) {
// expected
assertEquals(1, ex.getPossibleMatches().length);
assertEquals("age", ex.getPossibleMatches()[0]);
}
assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() ->
accessor.setPropertyValue("ag", "foobar"))
.satisfies(ex -> assertThat(ex.getPossibleMatches()).containsExactly("age"));
}
@Test // Can't be shared; there is no such thing as a read-only field
@ -214,14 +206,10 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests {
@Test
public void incompletelyQuotedKeyLeadsToPropertyException() {
TestBean target = new TestBean();
try {
BeanWrapper accessor = createAccessor(target);
accessor.setPropertyValue("[']", "foobar");
fail("Should throw exception on invalid property");
}
catch (NotWritablePropertyException ex) {
assertNull(ex.getPossibleMatches());
}
assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() ->
accessor.setPropertyValue("[']", "foobar"))
.satisfies(ex -> assertThat(ex.getPossibleMatches()).isNull());
}

View File

@ -30,7 +30,6 @@ import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Guillaume Poirier
@ -75,7 +74,7 @@ public class ConcurrentBeanWrapperTests {
}
}
if (ex != null) {
fail(ex.getMessage());
throw new AssertionError("Unexpected exception", ex);
}
}

View File

@ -33,7 +33,6 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author Chris Beams
@ -176,7 +175,7 @@ public class ExtendedBeanInfoTests {
return;
}
}
fail("never matched write method");
throw new AssertionError("never matched write method");
}
@Test
@ -671,7 +670,7 @@ public class ExtendedBeanInfoTests {
return;
}
}
fail("never matched write method");
throw new AssertionError("never matched write method");
}
@Test
@ -699,7 +698,7 @@ public class ExtendedBeanInfoTests {
return;
}
}
fail("never matched write method");
throw new AssertionError("never matched write method");
}
/**

View File

@ -20,13 +20,13 @@ import java.util.Iterator;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests for {@link MutablePropertyValues}.
@ -122,14 +122,7 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests {
PropertyValue pv = it.next();
assertEquals("foo", pv.getName());
assertEquals("bar", pv.getValue());
try {
it.remove();
fail("Should have thrown UnsupportedOperationException");
}
catch (UnsupportedOperationException ex) {
// expected
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(it::remove);
assertFalse(it.hasNext());
}

View File

@ -37,7 +37,6 @@ import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.springframework.tests.TestResourceUtils.qualifiedResource;
/**
@ -119,7 +118,7 @@ public class ConcurrentBeanFactoryTests {
}
}
if (ex != null) {
fail(ex.getMessage());
throw new AssertionError("Unexpected exception", ex);
}
}

View File

@ -99,7 +99,10 @@ import org.springframework.util.SerializationTestUtils;
import org.springframework.util.StopWatch;
import org.springframework.util.StringValueResolver;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
@ -110,7 +113,6 @@ import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
@ -581,20 +583,14 @@ public class DefaultListableBeanFactoryTests {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
Properties p = new Properties();
try {
p.setProperty(PREFIX + "kerry.(class)", TestBean.class.getName());
p.setProperty(PREFIX + "kerry.name", "Kerry");
p.setProperty(PREFIX + "kerry.age", "35");
p.setProperty(PREFIX + "kerry.spouse(ref)", "rod");
(new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p, PREFIX);
lbf.getBean("kerry");
fail("Unresolved reference should have been detected");
}
catch (BeansException ex) {
// cool
}
new PropertiesBeanDefinitionReader(lbf).registerBeanDefinitions(p, PREFIX);
assertThatExceptionOfType(BeansException.class).as("unresolved reference").isThrownBy(() ->
lbf.getBean("kerry"));
}
@Test
@ -611,23 +607,20 @@ public class DefaultListableBeanFactoryTests {
@Test
public void testPossibleMatches() {
try {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("ag", "foobar");
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.setPropertyValues(pvs);
lbf.registerBeanDefinition("tb", bd);
lbf.getBean("tb");
fail("Should throw exception on invalid property");
}
catch (BeanCreationException ex) {
assertTrue(ex.getCause() instanceof NotWritablePropertyException);
assertThatExceptionOfType(BeanCreationException.class).as("invalid property").isThrownBy(() ->
lbf.getBean("tb"))
.withCauseInstanceOf(NotWritablePropertyException.class)
.satisfies(ex -> {
NotWritablePropertyException cause = (NotWritablePropertyException) ex.getCause();
// expected
assertEquals(1, cause.getPossibleMatches().length);
assertEquals("age", cause.getPossibleMatches()[0]);
}
assertThat(cause.getPossibleMatches()).hasSize(1);
assertThat(cause.getPossibleMatches()[0]).isEqualTo("age");
});
}
@Test
@ -678,15 +671,10 @@ public class DefaultListableBeanFactoryTests {
p.setProperty("rod.age", "34");
p.setProperty("rod.spouse", "*kerry");
(new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p);
try {
lbf.getBean("kerry");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
// expected
assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
}
new PropertiesBeanDefinitionReader(lbf).registerBeanDefinitions(p);
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
lbf.getBean("kerry"))
.satisfies(ex -> assertThat(ex.contains(BeanCurrentlyInCreationException.class)).isTrue());
}
@Test
@ -804,23 +792,10 @@ public class DefaultListableBeanFactoryTests {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
lbf.registerAlias("test", "test2");
lbf.registerAlias("test2", "test3");
try {
lbf.registerAlias("test3", "test2");
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
try {
lbf.registerAlias("test3", "test");
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
lbf.registerAlias("test3", "test2"));
assertThatIllegalStateException().isThrownBy(() ->
lbf.registerAlias("test3", "test"));
lbf.registerAlias("test", "test3");
}
@ -857,15 +832,13 @@ public class DefaultListableBeanFactoryTests {
BeanDefinition oldDef = new RootBeanDefinition(TestBean.class);
BeanDefinition newDef = new RootBeanDefinition(NestedTestBean.class);
lbf.registerBeanDefinition("test", oldDef);
try {
lbf.registerBeanDefinition("test", newDef);
fail("Should have thrown BeanDefinitionOverrideException");
}
catch (BeanDefinitionOverrideException ex) {
assertEquals("test", ex.getBeanName());
assertSame(newDef, ex.getBeanDefinition());
assertSame(oldDef, ex.getExistingDefinition());
}
assertThatExceptionOfType(BeanDefinitionOverrideException.class).isThrownBy(() ->
lbf.registerBeanDefinition("test", newDef))
.satisfies(ex -> {
assertThat(ex.getBeanName()).isEqualTo("test");
assertThat(ex.getBeanDefinition()).isEqualTo(newDef);
assertThat(ex.getExistingDefinition()).isEqualTo(oldDef);
});
}
@Test
@ -1123,13 +1096,8 @@ public class DefaultListableBeanFactoryTests {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
Object singletonObject = new TestBean();
lbf.registerSingleton("singletonObject", singletonObject);
try {
lbf.registerSingleton("singletonObject", singletonObject);
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
lbf.registerSingleton("singletonObject", singletonObject));
}
@Test
@ -1301,15 +1269,10 @@ public class DefaultListableBeanFactoryTests {
lbf.registerBeanDefinition("rod", bd);
RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class);
lbf.registerBeanDefinition("rod2", bd2);
try {
lbf.autowire(ConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false);
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertTrue(ex.getMessage().contains("rod"));
assertTrue(ex.getMessage().contains("rod2"));
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
lbf.autowire(ConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false))
.withMessageContaining("rod")
.withMessageContaining("rod2");
}
@Test
@ -1321,13 +1284,8 @@ public class DefaultListableBeanFactoryTests {
bd.setPropertyValues(pvs);
lbf.registerBeanDefinition("rod", bd);
assertEquals(1, lbf.getBeanDefinitionCount());
try {
lbf.autowire(UnsatisfiedConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, true);
fail("Should have unsatisfied constructor dependency on SideEffectBean");
}
catch (UnsatisfiedDependencyException ex) {
// expected
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
lbf.autowire(UnsatisfiedConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, true));
}
@Test
@ -1359,13 +1317,8 @@ public class DefaultListableBeanFactoryTests {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
lbf.registerBeanDefinition("spous", bd);
try {
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true));
}
@Test
@ -1387,16 +1340,11 @@ public class DefaultListableBeanFactoryTests {
RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class);
bd2.setDependsOn("tb1");
lbf.registerBeanDefinition("tb2", bd2);
try {
lbf.preInstantiateSingletons();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
// expected
assertTrue(ex.getMessage().contains("Circular"));
assertTrue(ex.getMessage().contains("'tb2'"));
assertTrue(ex.getMessage().contains("'tb1'"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
lbf.preInstantiateSingletons())
.withMessageContaining("Circular")
.withMessageContaining("'tb2'")
.withMessageContaining("'tb1'");
}
@Test
@ -1411,22 +1359,18 @@ public class DefaultListableBeanFactoryTests {
RootBeanDefinition bd3 = new RootBeanDefinition(TestBean.class);
bd3.setDependsOn("tb1");
lbf.registerBeanDefinition("tb3", bd3);
try {
lbf.preInstantiateSingletons();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
// expected
assertTrue(ex.getMessage().contains("Circular"));
assertTrue(ex.getMessage().contains("'tb3'"));
assertTrue(ex.getMessage().contains("'tb1'"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
lbf::preInstantiateSingletons)
.withMessageContaining("Circular")
.withMessageContaining("'tb3'")
.withMessageContaining("'tb1'");
}
@Test(expected = NoSuchBeanDefinitionException.class)
@Test
public void testGetBeanByTypeWithNoneFound() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
lbf.getBean(TestBean.class);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
lbf.getBean(TestBean.class));
}
@Test
@ -1439,14 +1383,15 @@ public class DefaultListableBeanFactoryTests {
assertThat(bean.getBeanName(), equalTo("bd1"));
}
@Test(expected = NoUniqueBeanDefinitionException.class)
@Test
public void testGetBeanByTypeWithAmbiguity() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
RootBeanDefinition bd1 = new RootBeanDefinition(TestBean.class);
RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class);
lbf.registerBeanDefinition("bd1", bd1);
lbf.registerBeanDefinition("bd2", bd2);
lbf.getBean(TestBean.class);
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() ->
lbf.getBean(TestBean.class));
}
@Test
@ -1581,49 +1526,22 @@ public class DefaultListableBeanFactoryTests {
assertSame(lbf.getBean("bd1", TestBean.class), actual);
lbf.registerBeanDefinition("bd2", bd2);
try {
lbf.getBean(TestBean.class);
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
lbf.getBean(TestBean.class));
}
@Test
public void testGetBeanByTypeInstanceWithNoneFound() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
try {
lbf.getBean(ConstructorDependency.class);
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
try {
lbf.getBean(ConstructorDependency.class, 42);
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
lbf.getBean(ConstructorDependency.class));
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
lbf.getBean(ConstructorDependency.class, 42));
ObjectProvider<ConstructorDependency> provider = lbf.getBeanProvider(ConstructorDependency.class);
try {
provider.getObject();
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
try {
provider.getObject(42);
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(
provider::getObject);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
provider.getObject(42));
assertNull(provider.getIfAvailable());
assertNull(provider.getIfUnique());
}
@ -1666,44 +1584,17 @@ public class DefaultListableBeanFactoryTests {
bd2.getConstructorArgumentValues().addGenericArgumentValue("43");
lbf.registerBeanDefinition("bd1", bd1);
lbf.registerBeanDefinition("bd2", bd2);
try {
lbf.getBean(ConstructorDependency.class);
fail("Should have thrown NoUniqueBeanDefinitionException");
}
catch (NoUniqueBeanDefinitionException ex) {
// expected
}
try {
lbf.getBean(ConstructorDependency.class, 42);
fail("Should have thrown NoUniqueBeanDefinitionException");
}
catch (NoUniqueBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() ->
lbf.getBean(ConstructorDependency.class));
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() ->
lbf.getBean(ConstructorDependency.class, 42));
ObjectProvider<ConstructorDependency> provider = lbf.getBeanProvider(ConstructorDependency.class);
try {
provider.getObject();
fail("Should have thrown NoUniqueBeanDefinitionException");
}
catch (NoUniqueBeanDefinitionException ex) {
// expected
}
try {
provider.getObject(42);
fail("Should have thrown NoUniqueBeanDefinitionException");
}
catch (NoUniqueBeanDefinitionException ex) {
// expected
}
try {
provider.getIfAvailable();
fail("Should have thrown NoUniqueBeanDefinitionException");
}
catch (NoUniqueBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(
provider::getObject);
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() ->
provider.getObject(42));
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(
provider::getIfAvailable);
assertNull(provider.getIfUnique());
Set<Object> resolved = new HashSet<>();
@ -1805,13 +1696,8 @@ public class DefaultListableBeanFactoryTests {
assertThat(actual.beanName, equalTo("bd1"));
lbf.registerBeanDefinition("bd2", bd2);
try {
lbf.getBean(TestBean.class, 67);
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
lbf.getBean(TestBean.class, 67));
}
@Test
@ -1822,20 +1708,10 @@ public class DefaultListableBeanFactoryTests {
ObjectProvider<ConstructorDependency> provider = lbf.getBeanProvider(ConstructorDependency.class);
ObjectProvider deserialized = (ObjectProvider) SerializationTestUtils.serializeAndDeserialize(provider);
try {
deserialized.getObject();
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
try {
deserialized.getObject(42);
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(
deserialized::getObject);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
deserialized.getObject(42));
assertNull(deserialized.getIfAvailable());
assertNull(deserialized.getIfUnique());
}
@ -1976,14 +1852,15 @@ public class DefaultListableBeanFactoryTests {
* Java method names. In other words, you can't name a method
* {@code set&amp;FactoryBean(...)}.
*/
@Test(expected = TypeMismatchException.class)
@Test
public void testAutowireBeanWithFactoryBeanByName() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
RootBeanDefinition bd = new RootBeanDefinition(LazyInitFactory.class);
lbf.registerBeanDefinition("factoryBean", bd);
LazyInitFactory factoryBean = (LazyInitFactory) lbf.getBean("&factoryBean");
assertNotNull("The FactoryBean should have been registered.", factoryBean);
lbf.autowire(FactoryBeanDependentBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);
assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() ->
lbf.autowire(FactoryBeanDependentBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true));
}
@Test
@ -1993,27 +1870,17 @@ public class DefaultListableBeanFactoryTests {
RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class);
lbf.registerBeanDefinition("test", bd);
lbf.registerBeanDefinition("spouse", bd2);
try {
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertTrue(ex.getMessage().contains("test"));
assertTrue(ex.getMessage().contains("spouse"));
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true))
.withMessageContaining("test")
.withMessageContaining("spouse");
}
@Test
public void testAutowireBeanByTypeWithDependencyCheck() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
try {
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true));
}
@Test
@ -2047,16 +1914,9 @@ public class DefaultListableBeanFactoryTests {
bd2.setPrimary(true);
lbf.registerBeanDefinition("test", bd);
lbf.registerBeanDefinition("spouse", bd2);
try {
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertNotNull("Exception should have cause", ex.getCause());
assertEquals("Wrong cause type", NoUniqueBeanDefinitionException.class, ex.getCause().getClass());
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true))
.withCauseExactlyInstanceOf(NoUniqueBeanDefinitionException.class);
}
@Test
@ -2081,17 +1941,10 @@ public class DefaultListableBeanFactoryTests {
RootBeanDefinition bd2 = new RootBeanDefinition(HighPriorityTestBean.class);
lbf.registerBeanDefinition("test", bd);
lbf.registerBeanDefinition("spouse", bd2);
try {
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertNotNull("Exception should have cause", ex.getCause());
assertEquals("Wrong cause type", NoUniqueBeanDefinitionException.class, ex.getCause().getClass());
assertTrue(ex.getMessage().contains("5")); // conflicting priority
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true))
.withCauseExactlyInstanceOf(NoUniqueBeanDefinitionException.class)
.withMessageContaining("5");
}
@Test
@ -2127,13 +1980,8 @@ public class DefaultListableBeanFactoryTests {
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
lbf.registerBeanDefinition("spous", bd);
DependenciesBean existingBean = new DependenciesBean();
try {
lbf.autowireBeanProperties(existingBean, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
lbf.autowireBeanProperties(existingBean, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true));
}
@Test
@ -2161,12 +2009,8 @@ public class DefaultListableBeanFactoryTests {
public void testAutowireExistingBeanByTypeWithDependencyCheck() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
DependenciesBean existingBean = new DependenciesBean();
try {
lbf.autowireBeanProperties(existingBean, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException expected) {
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
lbf.autowireBeanProperties(existingBean, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true));
}
@Test
@ -2180,12 +2024,8 @@ public class DefaultListableBeanFactoryTests {
@Test
public void testInvalidAutowireMode() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
try {
lbf.autowireBeanProperties(new TestBean(), AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
lbf.autowireBeanProperties(new TestBean(), AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false));
}
@Test
@ -2292,12 +2132,8 @@ public class DefaultListableBeanFactoryTests {
RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependencyBean.class);
bd.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
lbf.registerBeanDefinition("test", bd);
try {
lbf.preInstantiateSingletons();
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException expected) {
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
lbf::preInstantiateSingletons);
}
@Test
@ -2306,12 +2142,8 @@ public class DefaultListableBeanFactoryTests {
RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependencyFactoryBean.class);
bd.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
lbf.registerBeanDefinition("test", bd);
try {
lbf.preInstantiateSingletons();
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException expected) {
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
lbf::preInstantiateSingletons);
}
@Test
@ -2320,12 +2152,8 @@ public class DefaultListableBeanFactoryTests {
RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependencyFactoryBean.class);
bd.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
lbf.registerBeanDefinition("test", bd);
try {
lbf.getBeansOfType(String.class);
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException expected) {
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
lbf.getBeansOfType(String.class));
}
@Test
@ -2355,41 +2183,28 @@ public class DefaultListableBeanFactoryTests {
RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependencyWithClassResolution.class);
bd.getConstructorArgumentValues().addGenericArgumentValue("java.lang.Strin");
lbf.registerBeanDefinition("test", bd);
try {
lbf.preInstantiateSingletons();
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException expected) {
assertTrue(expected.toString().contains("java.lang.Strin"));
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
lbf::preInstantiateSingletons);
}
@Test
public void testBeanDefinitionWithInterface() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
lbf.registerBeanDefinition("test", new RootBeanDefinition(ITestBean.class));
try {
lbf.getBean("test");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertEquals("test", ex.getBeanName());
assertTrue(ex.getMessage().toLowerCase().contains("interface"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
lbf.getBean("test"))
.withMessageContaining("interface")
.satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("test"));
}
@Test
public void testBeanDefinitionWithAbstractClass() {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
lbf.registerBeanDefinition("test", new RootBeanDefinition(AbstractBeanFactory.class));
try {
lbf.getBean("test");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertEquals("test", ex.getBeanName());
assertTrue(ex.getMessage().toLowerCase().contains("abstract"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
lbf.getBean("test"))
.withMessageContaining("abstract")
.satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("test"));
}
@Test
@ -2841,7 +2656,7 @@ public class DefaultListableBeanFactoryTests {
assertEquals(expectedNameFromArgs, tb2.getName());
}
@Test(expected = IllegalStateException.class)
@Test
public void testScopingBeanToUnregisteredScopeResultsInAnException() {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class);
AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
@ -2849,7 +2664,8 @@ public class DefaultListableBeanFactoryTests {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition("testBean", beanDefinition);
factory.getBean("testBean");
assertThatIllegalStateException().isThrownBy(() ->
factory.getBean("testBean"));
}
@Test
@ -2915,9 +2731,7 @@ public class DefaultListableBeanFactoryTests {
return !skipPropertyPopulation;
}
catch (Exception ex) {
fail("Unexpected exception: " + ex);
// Keep compiler happy about return
throw new IllegalStateException();
throw new AssertionError("Unexpected exception", ex);
}
}
});

View File

@ -23,9 +23,7 @@ import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
/**
@ -74,14 +72,9 @@ public class Spr5475Tests {
private void assertExceptionMessageForMisconfiguredFactoryMethod(BeanDefinition bd, String expectedMessage) {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition("foo", bd);
try {
factory.preInstantiateSingletons();
fail("should have failed with BeanCreationException due to incorrectly invoked factory method");
}
catch (BeanCreationException ex) {
assertThat(ex.getMessage(), equalTo(expectedMessage));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
factory::preInstantiateSingletons)
.withMessageContaining(expectedMessage);
}
@Test

View File

@ -20,11 +20,11 @@ import org.junit.Test;
import org.springframework.beans.factory.wiring.BeanWiringInfo;
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.fail;
/**
* @author Rick Evans
@ -34,12 +34,8 @@ public class AnnotationBeanWiringInfoResolverTests {
@Test
public void testResolveWiringInfo() throws Exception {
try {
new AnnotationBeanWiringInfoResolver().resolveWiringInfo(null);
fail("Must have thrown an IllegalArgumentException by this point (null argument)");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
new AnnotationBeanWiringInfoResolver().resolveWiringInfo(null));
}
@Test

View File

@ -36,6 +36,8 @@ import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.After;
@ -49,6 +51,7 @@ import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InjectionPoint;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.ObjectFactory;
@ -72,6 +75,8 @@ import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.SerializationTestUtils;
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;
@ -80,7 +85,6 @@ import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@ -116,13 +120,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
@Test
public void testIncompleteBeanDefinition() {
bf.registerBeanDefinition("testBean", new GenericBeanDefinition());
try {
bf.getBean("testBean");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.getRootCause() instanceof IllegalStateException);
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
bf.getBean("testBean"))
.withRootCauseInstanceOf(IllegalStateException.class);
}
@Test
@ -619,15 +619,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
@Test
public void testConstructorResourceInjectionWithNoCandidatesAndNoFallback() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ConstructorWithoutFallbackBean.class));
try {
bf.getBean("annotatedBean");
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertSame(ConstructorWithoutFallbackBean.class, ex.getInjectionPoint().getMethodParameter().getDeclaringClass());
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
bf.getBean("annotatedBean"))
.satisfies(methodParameterDeclaredOn(ConstructorWithoutFallbackBean.class));
}
@Test
@ -792,20 +786,21 @@ public class AutowiredAnnotationBeanPostProcessorTests {
assertNull(bean.getNestedTestBeans());
}
@Test(expected = UnsatisfiedDependencyException.class)
@Test
public void testSingleConstructorInjectionWithMissingDependency() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SingleConstructorOptionalCollectionBean.class));
bf.getBean("annotatedBean");
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
bf.getBean("annotatedBean"));
}
@Test(expected = UnsatisfiedDependencyException.class)
@Test
public void testSingleConstructorInjectionWithNullDependency() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SingleConstructorOptionalCollectionBean.class));
RootBeanDefinition tb = new RootBeanDefinition(NullFactoryMethods.class);
tb.setFactoryMethodName("createTestBean");
bf.registerBeanDefinition("testBean", tb);
bf.getBean("annotatedBean");
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
bf.getBean("annotatedBean"));
}
@Test
@ -901,15 +896,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class));
bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class));
bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
try {
bf.getBean("annotatedBean");
fail("should have failed, more than one bean of type");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertSame(MapMethodInjectionBean.class, ex.getInjectionPoint().getMethodParameter().getDeclaringClass());
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).as("should have failed, more than one bean of type").isThrownBy(() ->
bf.getBean("annotatedBean"))
.satisfies(methodParameterDeclaredOn(MapMethodInjectionBean.class));
}
@Test
@ -1222,13 +1211,8 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectProviderInjectionBean.class));
ObjectProviderInjectionBean bean = (ObjectProviderInjectionBean) bf.getBean("annotatedBean");
try {
bean.getTestBean();
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(
bean::getTestBean);
assertNull(bean.getOptionalTestBean());
assertNull(bean.consumeOptionalTestBean());
assertEquals(new TestBean("default"), bean.getOptionalTestBeanWithDefault());
@ -1253,27 +1237,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
ObjectProviderInjectionBean bean = (ObjectProviderInjectionBean) bf.getBean("annotatedBean");
try {
bean.getTestBean();
fail("Should have thrown NoUniqueBeanDefinitionException");
}
catch (NoUniqueBeanDefinitionException ex) {
// expected
}
try {
bean.getOptionalTestBean();
fail("Should have thrown NoUniqueBeanDefinitionException");
}
catch (NoUniqueBeanDefinitionException ex) {
// expected
}
try {
bean.consumeOptionalTestBean();
fail("Should have thrown NoUniqueBeanDefinitionException");
}
catch (NoUniqueBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(bean::getTestBean);
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(bean::getOptionalTestBean);
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(bean::consumeOptionalTestBean);
assertNull(bean.getUniqueTestBean());
assertNull(bean.consumeUniqueTestBean());
@ -1374,16 +1340,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bpp.setRequiredParameterValue(false);
bf.registerBeanDefinition("customBean", new RootBeanDefinition(
CustomAnnotationRequiredFieldResourceInjectionBean.class));
try {
bf.getBean("customBean");
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertSame(CustomAnnotationRequiredFieldResourceInjectionBean.class,
ex.getInjectionPoint().getField().getDeclaringClass());
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
bf.getBean("customBean"))
.satisfies(fieldDeclaredOn(CustomAnnotationRequiredFieldResourceInjectionBean.class));
}
@Test
@ -1397,16 +1356,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("testBean1", tb1);
TestBean tb2 = new TestBean();
bf.registerSingleton("testBean2", tb2);
try {
bf.getBean("customBean");
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertSame(CustomAnnotationRequiredFieldResourceInjectionBean.class,
ex.getInjectionPoint().getField().getDeclaringClass());
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
bf.getBean("customBean"))
.satisfies(fieldDeclaredOn(CustomAnnotationRequiredFieldResourceInjectionBean.class));
}
@Test
@ -1431,16 +1383,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bpp.setRequiredParameterValue(false);
bf.registerBeanDefinition("customBean", new RootBeanDefinition(
CustomAnnotationRequiredMethodResourceInjectionBean.class));
try {
bf.getBean("customBean");
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertSame(CustomAnnotationRequiredMethodResourceInjectionBean.class,
ex.getInjectionPoint().getMethodParameter().getDeclaringClass());
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
bf.getBean("customBean"))
.satisfies(methodParameterDeclaredOn(CustomAnnotationRequiredMethodResourceInjectionBean.class));
}
@Test
@ -1454,16 +1399,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("testBean1", tb1);
TestBean tb2 = new TestBean();
bf.registerSingleton("testBean2", tb2);
try {
bf.getBean("customBean");
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertSame(CustomAnnotationRequiredMethodResourceInjectionBean.class,
ex.getInjectionPoint().getMethodParameter().getDeclaringClass());
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
bf.getBean("customBean"))
.satisfies(methodParameterDeclaredOn(CustomAnnotationRequiredMethodResourceInjectionBean.class));
}
@Test
@ -1509,16 +1447,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("testBean1", tb1);
TestBean tb2 = new TestBean();
bf.registerSingleton("testBean2", tb2);
try {
bf.getBean("customBean");
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertSame(CustomAnnotationOptionalFieldResourceInjectionBean.class,
ex.getInjectionPoint().getField().getDeclaringClass());
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
bf.getBean("customBean"))
.satisfies(fieldDeclaredOn(CustomAnnotationOptionalFieldResourceInjectionBean.class));
}
@Test
@ -1564,16 +1495,9 @@ public class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("testBean1", tb1);
TestBean tb2 = new TestBean();
bf.registerSingleton("testBean2", tb2);
try {
bf.getBean("customBean");
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
// expected
assertSame(CustomAnnotationOptionalMethodResourceInjectionBean.class,
ex.getInjectionPoint().getMethodParameter().getDeclaringClass());
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
bf.getBean("customBean"))
.satisfies(methodParameterDeclaredOn(CustomAnnotationOptionalMethodResourceInjectionBean.class));
}
/**
@ -2219,6 +2143,30 @@ public class AutowiredAnnotationBeanPostProcessorTests {
assertSame(bf.getBean("annotatedBean"), bean.testBean);
}
private <E extends UnsatisfiedDependencyException> Consumer<E> methodParameterDeclaredOn(
Class<?> expected) {
return declaredOn(
injectionPoint -> injectionPoint.getMethodParameter().getDeclaringClass(),
expected);
}
private <E extends UnsatisfiedDependencyException> Consumer<E> fieldDeclaredOn(
Class<?> expected) {
return declaredOn(
injectionPoint -> injectionPoint.getField().getDeclaringClass(),
expected);
}
private <E extends UnsatisfiedDependencyException> Consumer<E> declaredOn(
Function<InjectionPoint, Class<?>> declaringClassExtractor,
Class<?> expected) {
return ex -> {
InjectionPoint injectionPoint = ex.getInjectionPoint();
Class<?> declaringClass = declaringClassExtractor.apply(injectionPoint);
assertThat(declaringClass).isSameAs(expected);
};
}
@Qualifier("testBean")
private void testBeanQualifierProvider() {}

View File

@ -45,6 +45,7 @@ import org.springframework.tests.sample.beans.NestedTestBean;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.SerializationTestUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@ -52,7 +53,6 @@ import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for {@link org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor}
@ -313,14 +313,8 @@ public class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class));
bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class));
bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
try {
bf.getBean("annotatedBean");
fail("should have failed, more than one bean of type");
}
catch (BeanCreationException e) {
// expected
}
assertThatExceptionOfType(BeanCreationException.class).as("should have failed, more than one bean of type").isThrownBy(() ->
bf.getBean("annotatedBean"));
}
@Test

View File

@ -23,10 +23,10 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
/**
* @author Karl Pietrzak
@ -95,12 +95,8 @@ public class LookupAnnotationTests {
public void testWithThreeArgsShouldFail() {
AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean");
assertNotNull(bean);
try {
bean.getThreeArguments("name", 1, 2);
fail("TestBean does not have a three arg constructor so this should not have worked");
}
catch (AbstractMethodError ex) {
}
assertThatExceptionOfType(AbstractMethodError.class).as("TestBean has no three arg constructor").isThrownBy(() ->
bean.getThreeArguments("name", 1, 2));
assertSame(bean, beanFactory.getBean(BeanConsumer.class).abstractBean);
}

View File

@ -32,9 +32,8 @@ import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@ -46,7 +45,6 @@ public class RequiredAnnotationBeanPostProcessorTests {
@Test
public void testWithRequiredPropertyOmitted() {
try {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinition beanDef = BeanDefinitionBuilder
.genericBeanDefinition(RequiredTestBean.class)
@ -56,20 +54,15 @@ public class RequiredAnnotationBeanPostProcessorTests {
.getBeanDefinition();
factory.registerBeanDefinition("testBean", beanDef);
factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
factory.preInstantiateSingletons();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
String message = ex.getCause().getMessage();
assertTrue(message.contains("Property"));
assertTrue(message.contains("age"));
assertTrue(message.contains("testBean"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
factory::preInstantiateSingletons)
.withMessageContaining("Property")
.withMessageContaining("age")
.withMessageContaining("testBean");
}
@Test
public void testWithThreeRequiredPropertiesOmitted() {
try {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinition beanDef = BeanDefinitionBuilder
.genericBeanDefinition(RequiredTestBean.class)
@ -77,17 +70,13 @@ public class RequiredAnnotationBeanPostProcessorTests {
.getBeanDefinition();
factory.registerBeanDefinition("testBean", beanDef);
factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
factory.preInstantiateSingletons();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
String message = ex.getCause().getMessage();
assertTrue(message.contains("Properties"));
assertTrue(message.contains("age"));
assertTrue(message.contains("favouriteColour"));
assertTrue(message.contains("jobTitle"));
assertTrue(message.contains("testBean"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
factory::preInstantiateSingletons)
.withMessageContaining("Properties")
.withMessageContaining("age")
.withMessageContaining("favouriteColour")
.withMessageContaining("jobTitle")
.withMessageContaining("testBean");
}
@Test
@ -109,7 +98,6 @@ public class RequiredAnnotationBeanPostProcessorTests {
@Test
public void testWithCustomAnnotation() {
try {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinition beanDef = BeanDefinitionBuilder
.genericBeanDefinition(RequiredTestBean.class)
@ -118,20 +106,15 @@ public class RequiredAnnotationBeanPostProcessorTests {
RequiredAnnotationBeanPostProcessor rabpp = new RequiredAnnotationBeanPostProcessor();
rabpp.setRequiredAnnotationType(MyRequired.class);
factory.addBeanPostProcessor(rabpp);
factory.preInstantiateSingletons();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
String message = ex.getCause().getMessage();
assertTrue(message.contains("Property"));
assertTrue(message.contains("name"));
assertTrue(message.contains("testBean"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
factory::preInstantiateSingletons)
.withMessageContaining("Property")
.withMessageContaining("name")
.withMessageContaining("testBean");
}
@Test
public void testWithStaticFactoryMethod() {
try {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinition beanDef = BeanDefinitionBuilder
.genericBeanDefinition(RequiredTestBean.class)
@ -142,15 +125,11 @@ public class RequiredAnnotationBeanPostProcessorTests {
.getBeanDefinition();
factory.registerBeanDefinition("testBean", beanDef);
factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
factory.preInstantiateSingletons();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
String message = ex.getCause().getMessage();
assertTrue(message.contains("Property"));
assertTrue(message.contains("age"));
assertTrue(message.contains("testBean"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
factory::preInstantiateSingletons)
.withMessageContaining("Property")
.withMessageContaining("age")
.withMessageContaining("testBean");
}
@Test

View File

@ -23,6 +23,8 @@ import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
@ -77,32 +79,35 @@ public class CustomScopeConfigurerTests {
assertTrue(factory.getRegisteredScope(FOO_SCOPE) instanceof NoOpScope);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWhereScopeMapHasNullScopeValueInEntrySet() {
Map<String, Object> scopes = new HashMap<>();
scopes.put(FOO_SCOPE, null);
CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.setScopes(scopes);
figurer.postProcessBeanFactory(factory);
assertThatIllegalArgumentException().isThrownBy(() ->
figurer.postProcessBeanFactory(factory));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWhereScopeMapHasNonScopeInstanceInEntrySet() {
Map<String, Object> scopes = new HashMap<>();
scopes.put(FOO_SCOPE, this); // <-- not a valid value...
CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.setScopes(scopes);
figurer.postProcessBeanFactory(factory);
assertThatIllegalArgumentException().isThrownBy(() ->
figurer.postProcessBeanFactory(factory));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test(expected = ClassCastException.class)
@Test
public void testWhereScopeMapHasNonStringTypedScopeNameInKeySet() {
Map scopes = new HashMap();
scopes.put(this, new NoOpScope()); // <-- not a valid value (the key)...
CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.setScopes(scopes);
figurer.postProcessBeanFactory(factory);
assertThatExceptionOfType(ClassCastException.class).isThrownBy(() ->
figurer.postProcessBeanFactory(factory));
}
}

View File

@ -26,11 +26,12 @@ import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.beans.support.ArgumentConvertingMethodInvoker;
import org.springframework.util.MethodInvoker;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for {@link MethodInvokingFactoryBean} and {@link MethodInvokingBean}.
@ -48,71 +49,35 @@ public class MethodInvokingFactoryBeanTests {
// assert that only static OR non static are set, but not both or none
MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean();
try {
mcfb.afterPropertiesSet();
fail(validationError);
}
catch (IllegalArgumentException ex) {
// expected
}
assertThatIllegalArgumentException().isThrownBy(mcfb::afterPropertiesSet);
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(this);
mcfb.setTargetMethod("whatever");
try {
mcfb.afterPropertiesSet();
fail(validationError);
}
catch (NoSuchMethodException ex) {
// expected
}
assertThatExceptionOfType(NoSuchMethodException.class).isThrownBy(mcfb::afterPropertiesSet);
// bogus static method
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("some.bogus.Method.name");
try {
mcfb.afterPropertiesSet();
fail(validationError);
}
catch (NoSuchMethodException ex) {
// expected
}
assertThatExceptionOfType(NoSuchMethodException.class).isThrownBy(mcfb::afterPropertiesSet);
// bogus static method
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("method1");
try {
mcfb.afterPropertiesSet();
fail(validationError);
}
catch (IllegalArgumentException ex) {
// expected
}
assertThatIllegalArgumentException().isThrownBy(mcfb::afterPropertiesSet);
// missing method
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(this);
try {
mcfb.afterPropertiesSet();
fail(validationError);
}
catch (IllegalArgumentException ex) {
// expected
}
assertThatIllegalArgumentException().isThrownBy(mcfb::afterPropertiesSet);
// bogus method
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetObject(this);
mcfb.setTargetMethod("bogus");
try {
mcfb.afterPropertiesSet();
fail(validationError);
}
catch (NoSuchMethodException ex) {
// expected
}
assertThatExceptionOfType(NoSuchMethodException.class).isThrownBy(mcfb::afterPropertiesSet);
// static method
TestClass1._staticField1 = 0;
@ -162,13 +127,7 @@ public class MethodInvokingFactoryBeanTests {
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments("1", new Object());
try {
mcfb.afterPropertiesSet();
fail("Should have thrown NoSuchMethodException");
}
catch (NoSuchMethodException ex) {
// expected
}
assertThatExceptionOfType(NoSuchMethodException.class).isThrownBy(mcfb::afterPropertiesSet);
}
@Test
@ -240,26 +199,17 @@ public class MethodInvokingFactoryBeanTests {
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), "hello", "bogus");
try {
mcfb.afterPropertiesSet();
fail("Matched method with wrong number of args");
}
catch (NoSuchMethodException ex) {
// expected
}
assertThatExceptionOfType(NoSuchMethodException.class).as(
"Matched method with wrong number of args").isThrownBy(
mcfb::afterPropertiesSet);
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes");
mcfb.setArguments(1, new Object());
try {
mcfb.afterPropertiesSet();
mcfb.getObject();
fail("Should have failed on getObject with mismatched argument types");
}
catch (NoSuchMethodException ex) {
// expected
}
assertThatExceptionOfType(NoSuchMethodException.class).as(
"Should have failed on getObject with mismatched argument types").isThrownBy(
mcfb::afterPropertiesSet);
mcfb = new MethodInvokingFactoryBean();
mcfb.setTargetClass(TestClass1.class);
@ -272,13 +222,9 @@ public class MethodInvokingFactoryBeanTests {
mcfb.setTargetClass(TestClass1.class);
mcfb.setTargetMethod("supertypes2");
mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), new Object());
try {
mcfb.afterPropertiesSet();
fail("Matched method when shouldn't have matched");
}
catch (NoSuchMethodException ex) {
// expected
}
assertThatExceptionOfType(NoSuchMethodException.class).as(
"Matched method when shouldn't have matched").isThrownBy(
mcfb::afterPropertiesSet);
}
@Test

View File

@ -29,10 +29,10 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.util.SerializationTestUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.tests.TestResourceUtils.qualifiedResource;
@ -127,33 +127,27 @@ public class ObjectFactoryCreatingFactoryBeanTests {
@Test
public void testWhenTargetBeanNameIsNull() throws Exception {
try {
new ObjectFactoryCreatingFactoryBean().afterPropertiesSet();
fail("Must have thrown an IllegalArgumentException; 'targetBeanName' property not set.");
}
catch (IllegalArgumentException expected) {}
assertThatIllegalArgumentException().as(
"'targetBeanName' property not set").isThrownBy(
new ObjectFactoryCreatingFactoryBean()::afterPropertiesSet);
}
@Test
public void testWhenTargetBeanNameIsEmptyString() throws Exception {
try {
ObjectFactoryCreatingFactoryBean factory = new ObjectFactoryCreatingFactoryBean();
factory.setTargetBeanName("");
factory.afterPropertiesSet();
fail("Must have thrown an IllegalArgumentException; 'targetBeanName' property set to (invalid) empty string.");
}
catch (IllegalArgumentException expected) {}
assertThatIllegalArgumentException().as(
"'targetBeanName' property set to (invalid) empty string").isThrownBy(
factory::afterPropertiesSet);
}
@Test
public void testWhenTargetBeanNameIsWhitespacedString() throws Exception {
try {
ObjectFactoryCreatingFactoryBean factory = new ObjectFactoryCreatingFactoryBean();
factory.setTargetBeanName(" \t");
factory.afterPropertiesSet();
fail("Must have thrown an IllegalArgumentException; 'targetBeanName' property set to (invalid) only-whitespace string.");
}
catch (IllegalArgumentException expected) {}
assertThatIllegalArgumentException().as(
"'targetBeanName' property set to (invalid) only-whitespace string").isThrownBy(
factory::afterPropertiesSet);
}
@Test

View File

@ -44,12 +44,12 @@ import org.springframework.tests.sample.beans.IndexedTestBean;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition;
import static org.springframework.tests.TestResourceUtils.qualifiedResource;
@ -481,35 +481,21 @@ public class PropertyResourceConfigurerTests {
public void testPropertyPlaceholderConfigurerWithUnresolvableSystemProperty() {
factory.registerBeanDefinition("tb", genericBeanDefinition(TestBean.class)
.addPropertyValue("touchy", "${user.dir}").getBeanDefinition());
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_NEVER);
try {
ppc.postProcessBeanFactory(factory);
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
assertTrue(ex.getMessage().contains("user.dir"));
}
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
ppc.postProcessBeanFactory(factory))
.withMessageContaining("user.dir");
}
@Test
public void testPropertyPlaceholderConfigurerWithUnresolvablePlaceholder() {
factory.registerBeanDefinition("tb", genericBeanDefinition(TestBean.class)
.addPropertyValue("name", "${ref}").getBeanDefinition());
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
try {
ppc.postProcessBeanFactory(factory);
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
assertTrue(ex.getMessage().contains("ref"));
}
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
ppc.postProcessBeanFactory(factory))
.withMessageContaining("ref");
}
@Test
@ -615,14 +601,8 @@ public class PropertyResourceConfigurerTests {
props.setProperty("var", "${m}");
props.setProperty("m", "${var}");
ppc.setProperties(props);
try {
ppc.postProcessBeanFactory(factory);
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
}
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
ppc.postProcessBeanFactory(factory));
}
@Test

View File

@ -27,11 +27,12 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.NestedCheckedException;
import org.springframework.core.NestedRuntimeException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
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.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition;
@ -80,27 +81,12 @@ public class ServiceLocatorFactoryBeanTests {
genericBeanDefinition(ServiceLocatorFactoryBean.class)
.addPropertyValue("serviceLocatorInterface", TestService2Locator.class)
.getBeanDefinition());
try {
TestServiceLocator factory = (TestServiceLocator) bf.getBean("factory");
factory.getTestService();
fail("Must fail on more than one matching type");
}
catch (NoSuchBeanDefinitionException ex) { /* expected */ }
try {
TestServiceLocator2 factory = (TestServiceLocator2) bf.getBean("factory2");
factory.getTestService(null);
fail("Must fail on more than one matching type");
}
catch (NoSuchBeanDefinitionException ex) { /* expected */ }
try {
TestService2Locator factory = (TestService2Locator) bf.getBean("factory3");
factory.getTestService();
fail("Must fail on no matching types");
}
catch (NoSuchBeanDefinitionException ex) { /* expected */ }
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).as("more than one matching type").isThrownBy(() ->
((TestServiceLocator) bf.getBean("factory")).getTestService());
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).as("more than one matching type").isThrownBy(() ->
((TestServiceLocator2) bf.getBean("factory2")).getTestService(null));
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).as("no matching types").isThrownBy(() ->
((TestService2Locator) bf.getBean("factory3")).getTestService());
}
@Test
@ -122,31 +108,14 @@ public class ServiceLocatorFactoryBeanTests {
.addPropertyValue("serviceLocatorInterface", TestService2Locator.class)
.addPropertyValue("serviceLocatorExceptionClass", CustomServiceLocatorException3.class)
.getBeanDefinition());
try {
TestServiceLocator factory = (TestServiceLocator) bf.getBean("factory");
factory.getTestService();
fail("Must fail on more than one matching type");
}
catch (CustomServiceLocatorException1 expected) {
assertTrue(expected.getCause() instanceof NoSuchBeanDefinitionException);
}
try {
TestServiceLocator2 factory2 = (TestServiceLocator2) bf.getBean("factory2");
factory2.getTestService(null);
fail("Must fail on more than one matching type");
}
catch (CustomServiceLocatorException2 expected) {
assertTrue(expected.getCause() instanceof NoSuchBeanDefinitionException);
}
try {
TestService2Locator factory3 = (TestService2Locator) bf.getBean("factory3");
factory3.getTestService();
fail("Must fail on no matching type");
}
catch (CustomServiceLocatorException3 ex) { /* expected */ }
assertThatExceptionOfType(CustomServiceLocatorException1.class).as("more than one matching type").isThrownBy(() ->
((TestServiceLocator) bf.getBean("factory")).getTestService())
.withCauseInstanceOf(NoSuchBeanDefinitionException.class);
assertThatExceptionOfType(CustomServiceLocatorException2.class).as("more than one matching type").isThrownBy(() ->
((TestServiceLocator2) bf.getBean("factory2")).getTestService(null))
.withCauseInstanceOf(NoSuchBeanDefinitionException.class);
assertThatExceptionOfType(CustomServiceLocatorException3.class).as("no matching type").isThrownBy(() ->
((TestService2Locator) bf.getBean("factory3")).getTestService());
}
@Test
@ -165,11 +134,8 @@ public class ServiceLocatorFactoryBeanTests {
// now test with explicit id
testBean = factory.getTestService("testService");
// now verify failure on bad id
try {
factory.getTestService("bogusTestService");
fail("Illegal operation allowed");
}
catch (NoSuchBeanDefinitionException ex) { /* expected */ }
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
factory.getTestService("bogusTestService"));
}
@Ignore @Test // worked when using an ApplicationContext (see commented), fails when using BeanFactory
@ -241,41 +207,46 @@ public class ServiceLocatorFactoryBeanTests {
assertTrue(testBean4 instanceof ExtendedTestService);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testNoServiceLocatorInterfaceSupplied() throws Exception {
new ServiceLocatorFactoryBean().afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(
new ServiceLocatorFactoryBean()::afterPropertiesSet);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWhenServiceLocatorInterfaceIsNotAnInterfaceType() throws Exception {
ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean();
factory.setServiceLocatorInterface(getClass());
factory.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(
factory::afterPropertiesSet);
// should throw, bad (non-interface-type) serviceLocator interface supplied
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWhenServiceLocatorExceptionClassToExceptionTypeWithOnlyNoArgCtor() throws Exception {
ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean();
factory.setServiceLocatorExceptionClass(ExceptionClassWithOnlyZeroArgCtor.class);
assertThatIllegalArgumentException().isThrownBy(() ->
factory.setServiceLocatorExceptionClass(ExceptionClassWithOnlyZeroArgCtor.class));
// should throw, bad (invalid-Exception-type) serviceLocatorException class supplied
}
@Test(expected = IllegalArgumentException.class)
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testWhenServiceLocatorExceptionClassIsNotAnExceptionSubclass() throws Exception {
ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean();
factory.setServiceLocatorExceptionClass((Class) getClass());
assertThatIllegalArgumentException().isThrownBy(() ->
factory.setServiceLocatorExceptionClass((Class) getClass()));
// should throw, bad (non-Exception-type) serviceLocatorException class supplied
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void testWhenServiceLocatorMethodCalledWithTooManyParameters() throws Exception {
ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean();
factory.setServiceLocatorInterface(ServiceLocatorInterfaceWithExtraNonCompliantMethod.class);
factory.afterPropertiesSet();
ServiceLocatorInterfaceWithExtraNonCompliantMethod locator = (ServiceLocatorInterfaceWithExtraNonCompliantMethod) factory.getObject();
locator.getTestService("not", "allowed"); //bad method (too many args, doesn't obey class contract)
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
locator.getTestService("not", "allowed")); //bad method (too many args, doesn't obey class contract)
}
@Test

View File

@ -28,6 +28,8 @@ import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@ -49,10 +51,12 @@ public class YamlMapFactoryBeanTests {
assertEquals(0, this.factory.getObject().size());
}
@Test(expected = IllegalStateException.class)
@Test
public void testSetBarfOnResourceNotFound() {
assertThatIllegalStateException().isThrownBy(() -> {
this.factory.setResources(new FileSystemResource("non-exsitent-file.yml"));
assertEquals(0, this.factory.getObject().size());
this.factory.getObject().size();
});
}
@Test
@ -118,10 +122,11 @@ public class YamlMapFactoryBeanTests {
assertEquals(Integer.valueOf(3), sub.get("key1.key2"));
}
@Test(expected = DuplicateKeyException.class)
@Test
public void testDuplicateKey() {
this.factory.setResources(new ByteArrayResource("mymap:\n foo: bar\nmymap:\n bar: foo".getBytes()));
this.factory.getObject().get("mymap");
assertThatExceptionOfType(DuplicateKeyException.class).isThrownBy(() ->
this.factory.getObject().get("mymap"));
}
}

View File

@ -76,20 +76,22 @@ public class YamlPropertiesFactoryBeanTests {
assertThat(properties.getProperty("foo.bar"), equalTo("spam"));
}
@Test(expected = DuplicateKeyException.class)
@Test
public void testLoadResourcesWithInternalOverride() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource(
"foo: bar\nspam:\n foo: baz\nfoo: bucket".getBytes()));
factory.getObject();
assertThatExceptionOfType(DuplicateKeyException.class).isThrownBy(
factory::getObject);
}
@Test(expected = DuplicateKeyException.class)
@Test
public void testLoadResourcesWithNestedInternalOverride() {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new ByteArrayResource(
"foo:\n bar: spam\n foo: baz\nbreak: it\nfoo: bucket".getBytes()));
factory.getObject();
assertThatExceptionOfType(DuplicateKeyException.class).isThrownBy(
factory::getObject);
}
@Test

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -18,6 +18,8 @@ package org.springframework.beans.factory.parsing;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Unit tests for {@link ConstructorArgumentEntry}.
*
@ -26,9 +28,10 @@ import org.junit.Test;
*/
public class ConstructorArgumentEntryTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorBailsOnNegativeCtorIndexArgument() {
new ConstructorArgumentEntry(-1);
assertThatIllegalArgumentException().isThrownBy(() ->
new ConstructorArgumentEntry(-1));
}
}

View File

@ -21,6 +21,7 @@ import org.junit.Test;
import org.springframework.core.io.DescriptiveResource;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.mock;
@ -33,11 +34,12 @@ import static org.mockito.Mockito.verify;
*/
public class FailFastProblemReporterTests {
@Test(expected = BeanDefinitionParsingException.class)
@Test
public void testError() throws Exception {
FailFastProblemReporter reporter = new FailFastProblemReporter();
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() ->
reporter.error(new Problem("VGER", new Location(new DescriptiveResource("here")),
null, new IllegalArgumentException()));
null, new IllegalArgumentException())));
}
@Test

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -18,6 +18,8 @@ package org.springframework.beans.factory.parsing;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Unit tests for {@link PropertyEntry}.
*
@ -26,19 +28,22 @@ import org.junit.Test;
*/
public class PropertyEntryTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorBailsOnNullPropertyNameArgument() throws Exception {
new PropertyEntry(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new PropertyEntry(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorBailsOnEmptyPropertyNameArgument() throws Exception {
new PropertyEntry("");
assertThatIllegalArgumentException().isThrownBy(() ->
new PropertyEntry(""));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorBailsOnWhitespacedPropertyNameArgument() throws Exception {
new PropertyEntry("\t ");
assertThatIllegalArgumentException().isThrownBy(() ->
new PropertyEntry("\t "));
}
}

View File

@ -56,13 +56,13 @@ import org.springframework.tests.sample.beans.GenericIntegerBean;
import org.springframework.tests.sample.beans.GenericSetOfIntegerBean;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@ -131,14 +131,12 @@ public class BeanFactoryGenericsTests {
rbd.getPropertyValues().add("testBeanList", input);
bf.registerBeanDefinition("genericBean", rbd);
try {
bf.getBean("genericBean");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.getMessage().contains("genericBean") && ex.getMessage().contains("testBeanList[0]"));
assertTrue(ex.getMessage().contains(TestBean.class.getName()) && ex.getMessage().contains("Integer"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
bf.getBean("genericBean"))
.withMessageContaining("genericBean")
.withMessageContaining("testBeanList[0]")
.withMessageContaining(TestBean.class.getName())
.withMessageContaining("Integer");
}
@Test
@ -883,20 +881,8 @@ public class BeanFactoryGenericsTests {
ObjectProvider<NumberStore<?>> numberStoreProvider = bf.getBeanProvider(ResolvableType.forClass(NumberStore.class));
ObjectProvider<NumberStore<Double>> doubleStoreProvider = bf.getBeanProvider(ResolvableType.forClassWithGenerics(NumberStore.class, Double.class));
ObjectProvider<NumberStore<Float>> floatStoreProvider = bf.getBeanProvider(ResolvableType.forClassWithGenerics(NumberStore.class, Float.class));
try {
numberStoreProvider.getObject();
fail("Should have thrown NoUniqueBeanDefinitionException");
}
catch (NoUniqueBeanDefinitionException ex) {
// expected
}
try {
numberStoreProvider.getIfAvailable();
fail("Should have thrown NoUniqueBeanDefinitionException");
}
catch (NoUniqueBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(numberStoreProvider::getObject);
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(numberStoreProvider::getIfAvailable);
assertNull(numberStoreProvider.getIfUnique());
assertSame(bf.getBean("store1"), doubleStoreProvider.getObject());
assertSame(bf.getBean("store1"), doubleStoreProvider.getIfAvailable());

View File

@ -23,10 +23,10 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Karl Pietrzak
@ -85,12 +85,8 @@ public class LookupMethodTests {
public void testWithThreeArgsShouldFail() {
AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean");
assertNotNull(bean);
try {
bean.getThreeArguments("name", 1, 2);
fail("TestBean does not have a three arg constructor so this should not have worked");
}
catch (AbstractMethodError ex) {
}
assertThatExceptionOfType(AbstractMethodError.class).as("does not have a three arg constructor").isThrownBy(() ->
bean.getThreeArguments("name", 1, 2));
}
@Test

View File

@ -20,6 +20,8 @@ import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
@ -51,18 +53,20 @@ public class ManagedListTests {
assertSame(child, child.merge(null));
}
@Test(expected = IllegalStateException.class)
@Test
public void mergeNotAllowedWhenMergeNotEnabled() {
ManagedList child = new ManagedList();
child.merge(null);
assertThatIllegalStateException().isThrownBy(() ->
child.merge(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void mergeWithNonCompatibleParentType() {
ManagedList child = new ManagedList();
child.add("one");
child.setMergeEnabled(true);
child.merge("hello");
assertThatIllegalArgumentException().isThrownBy(() ->
child.merge("hello"));
}
@Test

View File

@ -20,6 +20,8 @@ import java.util.Map;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
@ -50,16 +52,18 @@ public class ManagedMapTests {
assertSame(child, child.merge(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void mergeWithNonCompatibleParentType() {
ManagedMap map = new ManagedMap();
map.setMergeEnabled(true);
map.merge("hello");
assertThatIllegalArgumentException().isThrownBy(() ->
map.merge("hello"));
}
@Test(expected = IllegalStateException.class)
@Test
public void mergeNotAllowedWhenMergeNotEnabled() {
new ManagedMap().merge(null);
assertThatIllegalStateException().isThrownBy(() ->
new ManagedMap().merge(null));
}
@Test

View File

@ -20,6 +20,8 @@ import java.util.Map;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
@ -50,17 +52,19 @@ public class ManagedPropertiesTests {
assertSame(child, child.merge(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void mergeWithNonCompatibleParentType() {
ManagedProperties map = new ManagedProperties();
map.setMergeEnabled(true);
map.merge("hello");
assertThatIllegalArgumentException().isThrownBy(() ->
map.merge("hello"));
}
@Test(expected = IllegalStateException.class)
@Test
public void mergeNotAllowedWhenMergeNotEnabled() {
ManagedProperties map = new ManagedProperties();
map.merge(null);
assertThatIllegalStateException().isThrownBy(() ->
map.merge(null));
}
@Test

View File

@ -20,6 +20,8 @@ import java.util.Set;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
@ -51,17 +53,19 @@ public class ManagedSetTests {
assertSame(child, child.merge(null));
}
@Test(expected = IllegalStateException.class)
@Test
public void mergeNotAllowedWhenMergeNotEnabled() {
new ManagedSet().merge(null);
assertThatIllegalStateException().isThrownBy(() ->
new ManagedSet().merge(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void mergeWithNonCompatibleParentType() {
ManagedSet child = new ManagedSet();
child.add("one");
child.setMergeEnabled(true);
child.merge("hello");
assertThatIllegalArgumentException().isThrownBy(() ->
child.merge("hello"));
}
@Test

View File

@ -28,6 +28,7 @@ import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
import java.util.PropertyPermission;
import java.util.Set;
import java.util.function.Consumer;
import javax.security.auth.AuthPermission;
import javax.security.auth.Subject;
@ -50,14 +51,15 @@ import org.springframework.beans.factory.support.SecurityContextProvider;
import org.springframework.beans.factory.support.security.support.ConstructorBean;
import org.springframework.beans.factory.support.security.support.CustomCallbackBean;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.NestedRuntimeException;
import org.springframework.core.io.DefaultResourceLoader;
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.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Security test case. Checks whether the container uses its privileges for its
@ -325,68 +327,38 @@ public class CallbacksSecurityTests {
@Test
public void testSecuritySanity() throws Exception {
AccessControlContext acc = provider.getAccessControlContext();
try {
acc.checkPermission(new PropertyPermission("*", "read"));
fail("Acc should not have any permissions");
}
catch (SecurityException se) {
// expected
}
assertThatExceptionOfType(SecurityException.class).as(
"Acc should not have any permissions").isThrownBy(() ->
acc.checkPermission(new PropertyPermission("*", "read")));
final CustomCallbackBean bean = new CustomCallbackBean();
final Method method = bean.getClass().getMethod("destroy");
CustomCallbackBean bean = new CustomCallbackBean();
Method method = bean.getClass().getMethod("destroy");
method.setAccessible(true);
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
method.invoke(bean);
return null;
}
}, acc);
fail("expected security exception");
}
catch (Exception ex) {
}
}, acc));
final Class<ConstructorBean> cl = ConstructorBean.class;
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
return cl.newInstance();
}
}, acc);
fail("expected security exception");
}
catch (Exception ex) {
}
Class<ConstructorBean> cl = ConstructorBean.class;
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () ->
cl.newInstance(), acc));
}
@Test
public void testSpringInitBean() throws Exception {
try {
beanFactory.getBean("spring-init");
fail("expected security exception");
}
catch (BeanCreationException ex) {
assertTrue(ex.getCause() instanceof SecurityException);
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
beanFactory.getBean("spring-init"))
.withCauseInstanceOf(SecurityException.class);
}
@Test
public void testCustomInitBean() throws Exception {
try {
beanFactory.getBean("custom-init");
fail("expected security exception");
}
catch (BeanCreationException ex) {
assertTrue(ex.getCause() instanceof SecurityException);
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
beanFactory.getBean("custom-init"))
.withCauseInstanceOf(SecurityException.class);
}
@Test
@ -405,14 +377,9 @@ public class CallbacksSecurityTests {
@Test
public void testCustomFactoryObject() throws Exception {
try {
beanFactory.getBean("spring-factory");
fail("expected security exception");
}
catch (BeanCreationException ex) {
assertTrue(ex.getCause() instanceof SecurityException);
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
beanFactory.getBean("spring-factory"))
.withCauseInstanceOf(SecurityException.class);
}
@Test
@ -423,47 +390,30 @@ public class CallbacksSecurityTests {
@Test
public void testCustomStaticFactoryMethod() throws Exception {
try {
beanFactory.getBean("custom-static-factory-method");
fail("expected security exception");
}
catch (BeanCreationException ex) {
assertTrue(ex.getMostSpecificCause() instanceof SecurityException);
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
beanFactory.getBean("custom-static-factory-method"))
.satisfies(ex -> assertThat(ex.getMostSpecificCause()).isInstanceOf(SecurityException.class));
}
@Test
public void testCustomInstanceFactoryMethod() throws Exception {
try {
beanFactory.getBean("custom-factory-method");
fail("expected security exception");
}
catch (BeanCreationException ex) {
assertTrue(ex.getMostSpecificCause() instanceof SecurityException);
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
beanFactory.getBean("custom-factory-method"))
.satisfies(ex -> assertThat(ex.getMostSpecificCause()).isInstanceOf(SecurityException.class));
}
@Test
public void testTrustedFactoryMethod() throws Exception {
try {
beanFactory.getBean("privileged-static-factory-method");
fail("expected security exception");
}
catch (BeanCreationException ex) {
assertTrue(ex.getMostSpecificCause() instanceof SecurityException);
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
beanFactory.getBean("privileged-static-factory-method"))
.satisfies(mostSpecificCauseOf(SecurityException.class));
}
@Test
public void testConstructor() throws Exception {
try {
beanFactory.getBean("constructor");
fail("expected security exception");
}
catch (BeanCreationException ex) {
// expected
assertTrue(ex.getMostSpecificCause() instanceof SecurityException);
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
beanFactory.getBean("constructor"))
.satisfies(mostSpecificCauseOf(SecurityException.class));
}
@Test
@ -483,14 +433,9 @@ public class CallbacksSecurityTests {
@Test
public void testPropertyInjection() throws Exception {
try {
beanFactory.getBean("property-injection");
fail("expected security exception");
}
catch (BeanCreationException ex) {
assertTrue(ex.getMessage().contains("security"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
beanFactory.getBean("property-injection"))
.withMessageContaining("security");
beanFactory.getBean("working-property-injection");
}
@ -558,4 +503,9 @@ public class CallbacksSecurityTests {
}, provider.getAccessControlContext());
}
private <E extends NestedRuntimeException> Consumer<E> mostSpecificCauseOf(Class<? extends Throwable> type) {
return ex -> assertThat(ex.getMostSpecificCause()).isInstanceOf(type);
}
}

View File

@ -23,6 +23,7 @@ import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.BDDMockito.given;
@ -36,9 +37,10 @@ import static org.mockito.Mockito.verify;
*/
public class BeanConfigurerSupportTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void supplyIncompatibleBeanFactoryImplementation() throws Exception {
new StubBeanConfigurerSupport().setBeanFactory(mock(BeanFactory.class));
assertThatIllegalArgumentException().isThrownBy(() ->
new StubBeanConfigurerSupport().setBeanFactory(mock(BeanFactory.class)));
}
@Test

View File

@ -18,6 +18,7 @@ package org.springframework.beans.factory.wiring;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@ -29,29 +30,34 @@ import static org.junit.Assert.assertTrue;
*/
public class BeanWiringInfoTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void ctorWithNullBeanName() throws Exception {
new BeanWiringInfo(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new BeanWiringInfo(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void ctorWithWhitespacedBeanName() throws Exception {
new BeanWiringInfo(" \t");
assertThatIllegalArgumentException().isThrownBy(() ->
new BeanWiringInfo(" \t"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void ctorWithEmptyBeanName() throws Exception {
new BeanWiringInfo("");
assertThatIllegalArgumentException().isThrownBy(() ->
new BeanWiringInfo(""));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void ctorWithNegativeIllegalAutowiringValue() throws Exception {
new BeanWiringInfo(-1, true);
assertThatIllegalArgumentException().isThrownBy(() ->
new BeanWiringInfo(-1, true));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void ctorWithPositiveOutOfRangeAutowiringValue() throws Exception {
new BeanWiringInfo(123871, true);
assertThatIllegalArgumentException().isThrownBy(() ->
new BeanWiringInfo(123871, true));
}
@Test

View File

@ -18,6 +18,7 @@ package org.springframework.beans.factory.wiring;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@ -28,9 +29,10 @@ import static org.junit.Assert.assertNotNull;
*/
public class ClassNameBeanWiringInfoResolverTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void resolveWiringInfoWithNullBeanInstance() throws Exception {
new ClassNameBeanWiringInfoResolver().resolveWiringInfo(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new ClassNameBeanWiringInfoResolver().resolveWiringInfo(null));
}
@Test

View File

@ -34,11 +34,13 @@ import org.springframework.tests.sample.beans.MustBeInitialized;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.tests.sample.beans.factory.DummyFactory;
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.assertTrue;
import static org.junit.Assert.fail;
/**
* Subclasses must initialize the bean factory and any other variables they need.
@ -67,9 +69,10 @@ public abstract class AbstractBeanFactoryTests {
assertTrue("roderick.age was inherited", roderick.getAge() == rod.getAge());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void getBeanWithNullArg() {
getBeanFactory().getBean((String) null);
assertThatIllegalArgumentException().isThrownBy(() ->
getBeanFactory().getBean((String) null));
}
/**
@ -114,17 +117,13 @@ public abstract class AbstractBeanFactoryTests {
@Test
public void getInstanceByNonmatchingClass() {
try {
getBeanFactory().getBean("rod", BeanFactory.class);
fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
}
catch (BeanNotOfRequiredTypeException ex) {
// So far, so good
assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass());
}
assertThatExceptionOfType(BeanNotOfRequiredTypeException.class).isThrownBy(() ->
getBeanFactory().getBean("rod", BeanFactory.class))
.satisfies(ex -> {
assertThat(ex.getBeanName()).isEqualTo("rod");
assertThat(ex.getRequiredType()).isEqualTo(BeanFactory.class);
assertThat(ex.getActualType()).isEqualTo(TestBean.class).isEqualTo(getBeanFactory().getBean("rod").getClass());
});
}
@Test
@ -141,16 +140,13 @@ public abstract class AbstractBeanFactoryTests {
@Test
public void getSharedInstanceByNonmatchingClass() {
try {
getBeanFactory().getBean("rod", BeanFactory.class);
fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
}
catch (BeanNotOfRequiredTypeException ex) {
// So far, so good
assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
}
assertThatExceptionOfType(BeanNotOfRequiredTypeException.class).isThrownBy(() ->
getBeanFactory().getBean("rod", BeanFactory.class))
.satisfies(ex -> {
assertThat(ex.getBeanName()).isEqualTo("rod");
assertThat(ex.getRequiredType()).isEqualTo(BeanFactory.class);
assertThat(ex.getActualType()).isEqualTo(TestBean.class);
});
}
@Test
@ -175,10 +171,11 @@ public abstract class AbstractBeanFactoryTests {
assertTrue("object equal now false", !tb1.equals(tb2));
}
@Test(expected = BeansException.class)
@Test
public void notThere() {
assertFalse(getBeanFactory().containsBean("Mr Squiggle"));
getBeanFactory().getBean("Mr Squiggle");
assertThatExceptionOfType(BeansException.class).isThrownBy(() ->
getBeanFactory().getBean("Mr Squiggle"));
}
@Test
@ -190,19 +187,16 @@ public abstract class AbstractBeanFactoryTests {
}
public void xtestTypeMismatch() {
try {
getBeanFactory().getBean("typeMismatch");
fail("Shouldn't succeed with type mismatch");
}
catch (BeanCreationException wex) {
assertEquals("typeMismatch", wex.getBeanName());
assertTrue(wex.getCause() instanceof PropertyBatchUpdateException);
PropertyBatchUpdateException ex = (PropertyBatchUpdateException) wex.getCause();
// Further tests
assertTrue("Has one error ", ex.getExceptionCount() == 1);
assertTrue("Error is for field age", ex.getPropertyAccessException("age") != null);
assertTrue("We have rejected age in exception", ex.getPropertyAccessException("age").getPropertyChangeEvent().getNewValue().equals("34x"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
getBeanFactory().getBean("typeMismatch"))
.withCauseInstanceOf(PropertyBatchUpdateException.class)
.satisfies(ex -> {
assertThat(ex.getBeanName()).isEqualTo("typeMismatch");
PropertyBatchUpdateException pex = (PropertyBatchUpdateException) ex.getCause();
assertThat(pex.getExceptionCount()).isEqualTo(1);
assertThat(pex.getPropertyAccessException("age")).isNotNull();
assertThat(pex.getPropertyAccessException("age").getPropertyChangeEvent().getNewValue()).isEqualTo("34x");
});
}
@Test
@ -256,9 +250,10 @@ public abstract class AbstractBeanFactoryTests {
/**
* It should be illegal to dereference a normal bean as a factory.
*/
@Test(expected = BeanIsNotAFactoryException.class)
@Test
public void rejectsFactoryGetOnNormalBean() {
getBeanFactory().getBean("&rod");
assertThatExceptionOfType(BeanIsNotAFactoryException.class).isThrownBy(() ->
getBeanFactory().getBean("&rod"));
}
// TODO: refactor in AbstractBeanFactory (tests for AbstractBeanFactory)
@ -272,14 +267,10 @@ public abstract class AbstractBeanFactoryTests {
ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) bf;
String alias = "rods alias";
try {
cbf.getBean(alias);
fail("Shouldn't permit factory get on normal bean");
}
catch (NoSuchBeanDefinitionException ex) {
// Ok
assertTrue(alias.equals(ex.getBeanName()));
}
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
cbf.getBean(alias))
.satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo(alias));
// Create alias
cbf.registerAlias("rod", alias);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -20,6 +20,8 @@ import org.junit.Test;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Unit tests for the {@link DelegatingEntityResolver} class.
*
@ -28,19 +30,22 @@ import org.xml.sax.InputSource;
*/
public class DelegatingEntityResolverTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWhereDtdEntityResolverIsNull() throws Exception {
new DelegatingEntityResolver(null, new NoOpEntityResolver());
assertThatIllegalArgumentException().isThrownBy(() ->
new DelegatingEntityResolver(null, new NoOpEntityResolver()));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWhereSchemaEntityResolverIsNull() throws Exception {
new DelegatingEntityResolver(new NoOpEntityResolver(), null);
assertThatIllegalArgumentException().isThrownBy(() ->
new DelegatingEntityResolver(new NoOpEntityResolver(), null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWhereEntityResolversAreBothNull() throws Exception {
new DelegatingEntityResolver(null, null);
assertThatIllegalArgumentException().isThrownBy(() ->
new DelegatingEntityResolver(null, null));
}

View File

@ -22,9 +22,9 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
/**
* With Spring 3.1, bean id attributes (and all other id attributes across the
@ -46,13 +46,8 @@ public class DuplicateBeanIdTests {
public void duplicateBeanIdsWithinSameNestingLevelRaisesError() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf);
try {
reader.loadBeanDefinitions(new ClassPathResource("DuplicateBeanIdTests-sameLevel-context.xml", this.getClass()));
fail("expected parsing exception due to duplicate ids in same nesting level");
}
catch (Exception ex) {
// expected
}
assertThatExceptionOfType(Exception.class).as("duplicate ids in same nesting level").isThrownBy(() ->
reader.loadBeanDefinitions(new ClassPathResource("DuplicateBeanIdTests-sameLevel-context.xml", this.getClass())));
}
@Test

View File

@ -28,11 +28,11 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@ -79,14 +79,8 @@ public class FactoryMethodTests {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));
try {
xbf.getBean("defaultTestBeanWithInvalidDestroyMethod");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
// expected
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
xbf.getBean("defaultTestBeanWithInvalidDestroyMethod"));
}
@Test
@ -96,14 +90,8 @@ public class FactoryMethodTests {
reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));
assertEquals("null", xbf.getBean("null").toString());
try {
xbf.getBean("nullWithProperty");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
// expected
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
xbf.getBean("nullWithProperty"));
}
@Test
@ -253,13 +241,8 @@ public class FactoryMethodTests {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));
try {
xbf.getBean("noMatchPrototype");
fail("No static method matched");
}
catch (BeanCreationException ex) {
// Ok
}
assertThatExceptionOfType(BeanCreationException.class).as("No static method matched").isThrownBy(() ->
xbf.getBean("noMatchPrototype"));
}
@Test
@ -267,13 +250,9 @@ public class FactoryMethodTests {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));
try {
xbf.getBean("invalidPrototype");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.getMessage().contains("nonExisting(TestBean)"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
xbf.getBean("invalidPrototype"))
.withMessageContaining("nonExisting(TestBean)");
}
@Test
@ -281,13 +260,9 @@ public class FactoryMethodTests {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));
try {
xbf.getBean("invalidPrototype", new TestBean());
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.getMessage().contains("nonExisting(TestBean)"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
xbf.getBean("invalidPrototype", new TestBean()))
.withMessageContaining("nonExisting(TestBean)");
}
@Test

View File

@ -27,6 +27,7 @@ import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
@ -62,9 +63,10 @@ public class ProfileXmlBeanDefinitionTests {
private static final String TARGET_BEAN = "foo";
@Test(expected = IllegalArgumentException.class)
@Test
public void testProfileValidation() {
beanFactoryFor(PROD_ELIGIBLE_XML, NULL_ACTIVE);
assertThatIllegalArgumentException().isThrownBy(() ->
beanFactoryFor(PROD_ELIGIBLE_XML, NULL_ACTIVE));
}
@Test

View File

@ -24,10 +24,9 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@ -38,13 +37,9 @@ public class SchemaValidationTests {
public void withAutodetection() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf);
try {
reader.loadBeanDefinitions(new ClassPathResource("invalidPerSchema.xml", getClass()));
fail("Should not be able to parse a file with errors");
}
catch (BeansException ex) {
assertTrue(ex.getCause() instanceof SAXParseException);
}
assertThatExceptionOfType(BeansException.class).isThrownBy(() ->
reader.loadBeanDefinitions(new ClassPathResource("invalidPerSchema.xml", getClass())))
.withCauseInstanceOf(SAXParseException.class);
}
@Test
@ -52,13 +47,9 @@ public class SchemaValidationTests {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf);
reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
try {
reader.loadBeanDefinitions(new ClassPathResource("invalidPerSchema.xml", getClass()));
fail("Should not be able to parse a file with errors");
}
catch (BeansException ex) {
assertTrue(ex.getCause() instanceof SAXParseException);
}
assertThatExceptionOfType(BeansException.class).isThrownBy(() ->
reader.loadBeanDefinitions(new ClassPathResource("invalidPerSchema.xml", getClass())))
.withCauseInstanceOf(SAXParseException.class);
}
@Test

View File

@ -24,6 +24,7 @@ import org.springframework.core.io.ClassPathResource;
import org.springframework.tests.sample.beans.DummyBean;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
/**
@ -88,11 +89,12 @@ public class SimpleConstructorNamespaceHandlerTests {
assertEquals(beanFactory.getBean("name-value"), typeRef.getSpouse());
}
@Test(expected = BeanDefinitionStoreException.class)
@Test
public void ambiguousConstructor() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
new ClassPathResource("simpleConstructorNamespaceHandlerTestsWithErrors.xml", getClass()));
new ClassPathResource("simpleConstructorNamespaceHandlerTestsWithErrors.xml", getClass())));
}
@Test

View File

@ -24,6 +24,7 @@ import org.springframework.core.io.ClassPathResource;
import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
/**
@ -57,11 +58,12 @@ public class SimplePropertyNamespaceHandlerTests {
assertEquals(rob.getSpouse(), sally);
}
@Test(expected = BeanDefinitionStoreException.class)
@Test
public void withPropertyDefinedTwice() throws Exception {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions(
new ClassPathResource("simplePropertyNamespaceHandlerTestsWithErrors.xml", getClass()));
new ClassPathResource("simplePropertyNamespaceHandlerTestsWithErrors.xml", getClass())));
}
@Test

View File

@ -42,10 +42,10 @@ import org.springframework.core.io.ClassPathResource;
import org.springframework.tests.sample.beans.HasMap;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests for collections in XML bean definitions.
@ -178,14 +178,10 @@ public class XmlBeanCollectionTests {
@Test
public void testInvalidBeanNameReference() throws Exception {
try {
this.beanFactory.getBean("jumble2");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.getCause() instanceof BeanDefinitionStoreException);
assertTrue(ex.getCause().getMessage().contains("rod2"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
this.beanFactory.getBean("jumble2"))
.withCauseInstanceOf(BeanDefinitionStoreException.class)
.withMessageContaining("rod2");
}
@Test

View File

@ -31,6 +31,7 @@ import org.springframework.core.io.Resource;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.ObjectUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@ -48,11 +49,12 @@ public class XmlBeanDefinitionReaderTests {
new XmlBeanDefinitionReader(registry).setDocumentReaderClass(DefaultBeanDefinitionDocumentReader.class);
}
@Test(expected = BeanDefinitionStoreException.class)
@Test
public void withOpenInputStream() {
SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
Resource resource = new InputStreamResource(getClass().getResourceAsStream("test.xml"));
new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource);
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource));
}
@Test
@ -81,11 +83,12 @@ public class XmlBeanDefinitionReaderTests {
testBeanDefinitions(registry);
}
@Test(expected = BeanDefinitionStoreException.class)
@Test
public void withInputSource() {
SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
InputSource resource = new InputSource(getClass().getResourceAsStream("test.xml"));
new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource);
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource));
}
@Test

View File

@ -22,9 +22,9 @@ import org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver;
import org.springframework.beans.factory.xml.NamespaceHandler;
import org.springframework.beans.factory.xml.UtilNamespaceHandler;
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.fail;
/**
* Unit and integration tests for the {@link DefaultNamespaceHandlerResolver} class.
@ -53,13 +53,7 @@ public class DefaultNamespaceHandlerResolverTests {
@Test
public void testNonExistentHandlerClass() {
String mappingPath = "org/springframework/beans/factory/xml/support/nonExistent.properties";
try {
new DefaultNamespaceHandlerResolver(getClass().getClassLoader(), mappingPath);
// pass
}
catch (Throwable ex) {
fail("Non-existent handler classes must be ignored: " + ex);
}
}
@Test
@ -68,9 +62,10 @@ public class DefaultNamespaceHandlerResolverTests {
new DefaultNamespaceHandlerResolver(null);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWithNullClassLoaderArgumentAndNullMappingLocationArgument() {
new DefaultNamespaceHandlerResolver(null, null);
assertThatIllegalArgumentException().isThrownBy(() ->
new DefaultNamespaceHandlerResolver(null, null));
}
@Test

View File

@ -22,6 +22,7 @@ import java.util.List;
import org.junit.Test;
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;
@ -34,21 +35,24 @@ import static org.junit.Assert.assertTrue;
*/
public class CustomCollectionEditorTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWithNullCollectionType() throws Exception {
new CustomCollectionEditor(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new CustomCollectionEditor(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testCtorWithNonCollectionType() throws Exception {
new CustomCollectionEditor((Class) String.class);
assertThatIllegalArgumentException().isThrownBy(() ->
new CustomCollectionEditor((Class) String.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithCollectionTypeThatDoesNotExposeAPublicNoArgCtor() throws Exception {
CustomCollectionEditor editor = new CustomCollectionEditor(CollectionTypeWithNoNoArgCtor.class);
editor.setValue("1");
assertThatIllegalArgumentException().isThrownBy(() ->
editor.setValue("1"));
}
@Test

View File

@ -49,12 +49,14 @@ import org.springframework.tests.sample.beans.IndexedTestBean;
import org.springframework.tests.sample.beans.NumberTestBean;
import org.springframework.tests.sample.beans.TestBean;
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.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for the various PropertyEditors in Spring.
@ -223,13 +225,8 @@ public class CustomEditorTests {
bw.setPropertyValue("bool1", "0");
assertTrue("Correct bool1 value", !tb.isBool1());
try {
bw.setPropertyValue("bool1", "argh");
fail("Should have thrown BeansException");
}
catch (BeansException ex) {
// expected
}
assertThatExceptionOfType(BeansException.class).isThrownBy(() ->
bw.setPropertyValue("bool1", "argh"));
}
@Test
@ -324,14 +321,8 @@ public class CustomEditorTests {
editor.setAsText(falseString.toUpperCase());
assertFalse(((Boolean) editor.getValue()).booleanValue());
assertEquals(falseString, editor.getAsText());
try {
editor.setAsText(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
assertThatIllegalArgumentException().isThrownBy(() ->
editor.setAsText(null));
}
@Test
@ -453,16 +444,10 @@ public class CustomEditorTests {
bw.setPropertyValue("long2", "");
assertTrue("Correct long2 value", bw.getPropertyValue("long2") == null);
assertTrue("Correct long2 value", tb.getLong2() == null);
try {
bw.setPropertyValue("long1", "");
fail("Should have thrown BeansException");
}
catch (BeansException ex) {
// expected
assertTrue("Correct long1 value", new Long("5").equals(bw.getPropertyValue("long1")));
assertTrue("Correct long1 value", tb.getLong1() == 5);
}
assertThatExceptionOfType(BeansException.class).isThrownBy(() ->
bw.setPropertyValue("long1", ""));
assertThat(bw.getPropertyValue("long1")).isEqualTo(5L);
assertThat(tb.getLong1()).isEqualTo(5);
}
@Test
@ -481,14 +466,9 @@ public class CustomEditorTests {
@Test
public void testParseShortGreaterThanMaxValueWithoutNumberFormat() {
try {
CustomNumberEditor editor = new CustomNumberEditor(Short.class, true);
editor.setAsText(String.valueOf(Short.MAX_VALUE + 1));
fail(Short.MAX_VALUE + 1 + " is greater than max value");
}
catch (NumberFormatException ex) {
// expected
}
assertThatExceptionOfType(NumberFormatException.class).as("greater than Short.MAX_VALUE + 1").isThrownBy(() ->
editor.setAsText(String.valueOf(Short.MAX_VALUE + 1)));
}
@Test
@ -551,10 +531,11 @@ public class CustomEditorTests {
assertNull(cb.getMyCharacter());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCharacterEditorSetAsTextWithStringLongerThanOneCharacter() throws Exception {
PropertyEditor charEditor = new CharacterEditor(false);
charEditor.setAsText("ColdWaterCanyon");
assertThatIllegalArgumentException().isThrownBy(() ->
charEditor.setAsText("ColdWaterCanyon"));
}
@Test
@ -570,10 +551,11 @@ public class CustomEditorTests {
assertEquals(" ", charEditor.getAsText());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCharacterEditorSetAsTextWithNullNotAllowingEmptyAsNull() throws Exception {
PropertyEditor charEditor = new CharacterEditor(false);
charEditor.setAsText(null);
assertThatIllegalArgumentException().isThrownBy(() ->
charEditor.setAsText(null));
}
@Test
@ -591,10 +573,11 @@ public class CustomEditorTests {
assertEquals("", classEditor.getAsText());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testClassEditorWithNonExistentClass() throws Exception {
PropertyEditor classEditor = new ClassEditor();
classEditor.setAsText("hairdresser.on.Fire");
assertThatIllegalArgumentException().isThrownBy(() ->
classEditor.setAsText("hairdresser.on.Fire"));
}
@Test
@ -706,13 +689,8 @@ public class CustomEditorTests {
assertEquals(null, editor.getValue());
assertEquals("", editor.getAsText());
try {
editor.setAsText(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
assertThatIllegalArgumentException().isThrownBy(() ->
editor.setAsText(null));
}
@Test
@ -758,22 +736,10 @@ public class CustomEditorTests {
assertFalse(invalidDate.length() == maxLength);
CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true, maxLength);
try {
editor.setAsText(validDate);
}
catch (IllegalArgumentException ex) {
fail("Exception shouldn't be thrown because this is a valid date");
}
try {
editor.setAsText(invalidDate);
fail("Exception should be thrown because this is an invalid date");
}
catch (IllegalArgumentException ex) {
// expected
assertTrue(ex.getMessage().contains("10"));
}
assertThatIllegalArgumentException().isThrownBy(() ->
editor.setAsText(invalidDate))
.withMessageContaining("10");
}
@Test

View File

@ -23,6 +23,7 @@ import org.junit.Test;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@ -44,10 +45,11 @@ public class FileEditorTests {
assertTrue(file.exists());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithNonExistentResource() throws Exception {
PropertyEditor propertyEditor = new FileEditor();
propertyEditor.setAsText("classpath:no_way_this_file_is_found.doc");
assertThatIllegalArgumentException().isThrownBy(() ->
propertyEditor.setAsText("classpath:no_way_this_file_is_found.doc"));
}
@Test

View File

@ -22,6 +22,7 @@ import org.junit.Test;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@ -34,9 +35,10 @@ import static org.junit.Assert.assertTrue;
*/
public class InputStreamEditorTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWithNullResourceEditor() throws Exception {
new InputStreamEditor(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new InputStreamEditor(null));
}
@Test
@ -60,10 +62,11 @@ public class InputStreamEditorTests {
}
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWhenResourceDoesNotExist() throws Exception {
InputStreamEditor editor = new InputStreamEditor();
editor.setAsText("classpath:bingo!");
assertThatIllegalArgumentException().isThrownBy(() ->
editor.setAsText("classpath:bingo!"));
}
@Test

View File

@ -24,6 +24,7 @@ import org.junit.Test;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@ -44,10 +45,11 @@ public class PathEditorTests {
assertTrue(path.toFile().exists());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithNonExistentResource() throws Exception {
PropertyEditor propertyEditor = new PathEditor();
propertyEditor.setAsText("classpath:/no_way_this_file_is_found.doc");
assertThatIllegalArgumentException().isThrownBy(() ->
propertyEditor.setAsText("classpath:/no_way_this_file_is_found.doc"));
}
@Test

View File

@ -22,6 +22,7 @@ import org.junit.Test;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@ -34,9 +35,10 @@ import static org.junit.Assert.assertTrue;
*/
public class ReaderEditorTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWithNullResourceEditor() throws Exception {
new ReaderEditor(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new ReaderEditor(null));
}
@Test
@ -60,11 +62,12 @@ public class ReaderEditorTests {
}
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWhenResourceDoesNotExist() throws Exception {
String resource = "classpath:bingo!";
ReaderEditor editor = new ReaderEditor();
editor.setAsText(resource);
assertThatIllegalArgumentException().isThrownBy(() ->
editor.setAsText(resource));
}
@Test

View File

@ -20,6 +20,7 @@ import java.util.ResourceBundle;
import org.junit.Test;
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;
@ -102,28 +103,32 @@ public class ResourceBundleEditorTests {
assertEquals("ned", string);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSetAsTextWithNull() throws Exception {
ResourceBundleEditor editor = new ResourceBundleEditor();
editor.setAsText(null);
assertThatIllegalArgumentException().isThrownBy(() ->
editor.setAsText(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSetAsTextWithEmptyString() throws Exception {
ResourceBundleEditor editor = new ResourceBundleEditor();
editor.setAsText("");
assertThatIllegalArgumentException().isThrownBy(() ->
editor.setAsText(""));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSetAsTextWithWhiteSpaceString() throws Exception {
ResourceBundleEditor editor = new ResourceBundleEditor();
editor.setAsText(" ");
assertThatIllegalArgumentException().isThrownBy(() ->
editor.setAsText(" "));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSetAsTextWithJustSeparatorString() throws Exception {
ResourceBundleEditor editor = new ResourceBundleEditor();
editor.setAsText("_");
assertThatIllegalArgumentException().isThrownBy(() ->
editor.setAsText("_"));
}
}

View File

@ -23,6 +23,7 @@ import org.junit.Test;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@ -33,9 +34,10 @@ import static org.junit.Assert.assertTrue;
*/
public class URLEditorTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWithNullResourceEditor() throws Exception {
new URLEditor(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new URLEditor(null));
}
@Test
@ -70,10 +72,11 @@ public class URLEditorTests {
assertTrue(!url.getProtocol().startsWith("classpath"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithNonExistentResource() throws Exception {
PropertyEditor urlEditor = new URLEditor();
urlEditor.setAsText("gonna:/freak/in/the/morning/freak/in/the.evening");
assertThatIllegalArgumentException().isThrownBy(() ->
urlEditor.setAsText("gonna:/freak/in/the/morning/freak/in/the.evening"));
}
@Test

View File

@ -29,11 +29,11 @@ import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@ -63,11 +63,11 @@ public class EhCacheSupportTests {
@Test
public void testCacheManagerConflict() {
EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean();
try {
cacheManagerFb.setCacheManagerName("myCacheManager");
assertEquals(CacheManager.class, cacheManagerFb.getObjectType());
assertTrue("Singleton property", cacheManagerFb.isSingleton());
cacheManagerFb.afterPropertiesSet();
try {
CacheManager cm = cacheManagerFb.getObject();
assertTrue("Loaded CacheManager with no caches", cm.getCacheNames().length == 0);
Cache myCache1 = cm.getCache("myCache1");
@ -75,11 +75,8 @@ public class EhCacheSupportTests {
EhCacheManagerFactoryBean cacheManagerFb2 = new EhCacheManagerFactoryBean();
cacheManagerFb2.setCacheManagerName("myCacheManager");
cacheManagerFb2.afterPropertiesSet();
fail("Should have thrown CacheException because of naming conflict");
}
catch (CacheException ex) {
// expected
assertThatExceptionOfType(CacheException.class).as("because of naming conflict").isThrownBy(
cacheManagerFb2::afterPropertiesSet);
}
finally {
cacheManagerFb.destroy();

View File

@ -29,14 +29,16 @@ import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.context.ApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
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.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Stephane Nicoll
@ -99,13 +101,8 @@ public abstract class AbstractJCacheAnnotationTests {
Object key = createKey(keyItem);
assertNull(cache.get(key));
try {
service.cacheWithException(keyItem, true);
fail("Should have thrown an exception");
}
catch (UnsupportedOperationException e) {
// This is what we expect
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
service.cacheWithException(keyItem, true));
Cache.ValueWrapper result = cache.get(key);
assertNotNull(result);
@ -120,13 +117,8 @@ public abstract class AbstractJCacheAnnotationTests {
Object key = createKey(keyItem);
assertNull(cache.get(key));
try {
service.cacheWithException(keyItem, false);
fail("Should have thrown an exception");
}
catch (NullPointerException e) {
// This is what we expect
}
assertThatNullPointerException().isThrownBy(() ->
service.cacheWithException(keyItem, false));
assertNull(cache.get(key));
}
@ -137,14 +129,8 @@ public abstract class AbstractJCacheAnnotationTests {
Object key = createKey(keyItem);
assertNull(cache.get(key));
try {
service.cacheWithCheckedException(keyItem, true);
fail("Should have thrown an exception");
}
catch (IOException e) {
// This is what we expect
}
assertThatIOException().isThrownBy(() ->
service.cacheWithCheckedException(keyItem, true));
Cache.ValueWrapper result = cache.get(key);
assertNotNull(result);
@ -155,30 +141,26 @@ public abstract class AbstractJCacheAnnotationTests {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Test
public void cacheExceptionRewriteCallStack() {
final String keyItem = name.getMethodName();
UnsupportedOperationException first = null;
String keyItem = name.getMethodName();
long ref = service.exceptionInvocations();
try {
service.cacheWithException(keyItem, true);
fail("Should have thrown an exception");
}
catch (UnsupportedOperationException e) {
first = e;
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
service.cacheWithException(keyItem, true))
.satisfies(first -> {
// Sanity check, this particular call has called the service
assertEquals("First call should not have been cached", ref + 1, service.exceptionInvocations());
// First call should not have been cached
assertThat(service.exceptionInvocations()).isEqualTo(ref + 1);
UnsupportedOperationException second = methodInCallStack(keyItem);
// Sanity check, this particular call has *not* called the service
assertEquals("Second call should have been cached", ref + 1, service.exceptionInvocations());
// Second call should have been cached
assertThat(service.exceptionInvocations()).isEqualTo(ref + 1);
assertEquals(first.getCause(), second.getCause());
assertEquals(first.getMessage(), second.getMessage());
assertFalse("Original stack must not contain any reference to methodInCallStack",
contain(first, AbstractJCacheAnnotationTests.class.getName(), "methodInCallStack"));
assertTrue("Cached stack should have been rewritten with a reference to methodInCallStack",
contain(second, AbstractJCacheAnnotationTests.class.getName(), "methodInCallStack"));
assertThat(first).hasCause(second.getCause());
assertThat(first).hasMessage(second.getMessage());
// Original stack must not contain any reference to methodInCallStack
assertThat(contain(first, AbstractJCacheAnnotationTests.class.getName(), "methodInCallStack")).isFalse();
assertThat(contain(second, AbstractJCacheAnnotationTests.class.getName(), "methodInCallStack")).isTrue();
});
}
@Test
@ -246,13 +228,8 @@ public abstract class AbstractJCacheAnnotationTests {
Object value = new Object();
assertNull(cache.get(key));
try {
service.putWithException(keyItem, value, true);
fail("Should have thrown an exception");
}
catch (UnsupportedOperationException e) {
// This is what we expect
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
service.putWithException(keyItem, value, true));
Cache.ValueWrapper result = cache.get(key);
assertNotNull(result);
@ -268,13 +245,8 @@ public abstract class AbstractJCacheAnnotationTests {
Object value = new Object();
assertNull(cache.get(key));
try {
service.putWithException(keyItem, value, false);
fail("Should have thrown an exception");
}
catch (NullPointerException e) {
// This is what we expect
}
assertThatNullPointerException().isThrownBy(() ->
service.putWithException(keyItem, value, false));
assertNull(cache.get(key));
}
@ -303,13 +275,8 @@ public abstract class AbstractJCacheAnnotationTests {
Object value = new Object();
assertNull(cache.get(key));
try {
service.earlyPutWithException(keyItem, value, true);
fail("Should have thrown an exception");
}
catch (UnsupportedOperationException e) {
// This is what we expect
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
service.earlyPutWithException(keyItem, value, true));
Cache.ValueWrapper result = cache.get(key);
assertNotNull(result);
@ -324,14 +291,8 @@ public abstract class AbstractJCacheAnnotationTests {
Object key = createKey(keyItem);
Object value = new Object();
assertNull(cache.get(key));
try {
service.earlyPutWithException(keyItem, value, false);
fail("Should have thrown an exception");
}
catch (NullPointerException e) {
// This is what we expect
}
assertThatNullPointerException().isThrownBy(() ->
service.earlyPutWithException(keyItem, value, false));
// This will be cached anyway as the earlyPut has updated the cache before
Cache.ValueWrapper result = cache.get(key);
assertNotNull(result);
@ -361,13 +322,8 @@ public abstract class AbstractJCacheAnnotationTests {
Object value = new Object();
cache.put(key, value);
try {
service.removeWithException(keyItem, true);
fail("Should have thrown an exception");
}
catch (UnsupportedOperationException e) {
// This is what we expect
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
service.removeWithException(keyItem, true));
assertNull(cache.get(key));
}
@ -381,13 +337,8 @@ public abstract class AbstractJCacheAnnotationTests {
Object value = new Object();
cache.put(key, value);
try {
service.removeWithException(keyItem, false);
fail("Should have thrown an exception");
}
catch (NullPointerException e) {
// This is what we expect
}
assertThatNullPointerException().isThrownBy(() ->
service.removeWithException(keyItem, false));
Cache.ValueWrapper wrapper = cache.get(key);
assertNotNull(wrapper);
assertEquals(value, wrapper.get());
@ -416,13 +367,8 @@ public abstract class AbstractJCacheAnnotationTests {
Object value = new Object();
cache.put(key, value);
try {
service.earlyRemoveWithException(keyItem, true);
fail("Should have thrown an exception");
}
catch (UnsupportedOperationException e) {
// This is what we expect
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
service.earlyRemoveWithException(keyItem, true));
assertNull(cache.get(key));
}
@ -435,13 +381,8 @@ public abstract class AbstractJCacheAnnotationTests {
Object value = new Object();
cache.put(key, value);
try {
service.earlyRemoveWithException(keyItem, false);
fail("Should have thrown an exception");
}
catch (NullPointerException e) {
// This is what we expect
}
assertThatNullPointerException().isThrownBy(() ->
service.earlyRemoveWithException(keyItem, false));
// This will be remove anyway as the earlyRemove has removed the cache before
assertNull(cache.get(key));
}
@ -465,13 +406,8 @@ public abstract class AbstractJCacheAnnotationTests {
Object key = createKey(name.getMethodName());
cache.put(key, new Object());
try {
service.removeAllWithException(true);
fail("Should have thrown an exception");
}
catch (UnsupportedOperationException e) {
// This is what we expect
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
service.removeAllWithException(true));
assertTrue(isEmpty(cache));
}
@ -483,13 +419,8 @@ public abstract class AbstractJCacheAnnotationTests {
Object key = createKey(name.getMethodName());
cache.put(key, new Object());
try {
service.removeAllWithException(false);
fail("Should have thrown an exception");
}
catch (NullPointerException e) {
// This is what we expect
}
assertThatNullPointerException().isThrownBy(() ->
service.removeAllWithException(false));
assertNotNull(cache.get(key));
}
@ -512,13 +443,8 @@ public abstract class AbstractJCacheAnnotationTests {
Object key = createKey(name.getMethodName());
cache.put(key, new Object());
try {
service.earlyRemoveAllWithException(true);
fail("Should have thrown an exception");
}
catch (UnsupportedOperationException e) {
// This is what we expect
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
service.earlyRemoveAllWithException(true));
assertTrue(isEmpty(cache));
}
@ -529,13 +455,8 @@ public abstract class AbstractJCacheAnnotationTests {
Object key = createKey(name.getMethodName());
cache.put(key, new Object());
try {
service.earlyRemoveAllWithException(false);
fail("Should have thrown an exception");
}
catch (NullPointerException e) {
// This is what we expect
}
assertThatNullPointerException().isThrownBy(() ->
service.earlyRemoveAllWithException(false));
// This will be remove anyway as the earlyRemove has removed the cache before
assertTrue(isEmpty(cache));
}

View File

@ -38,9 +38,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
/**
* @author Stephane Nicoll
@ -85,17 +84,9 @@ public class JCacheCustomInterceptorTests {
@Test
public void customInterceptorAppliesWithCheckedException() {
try {
cs.cacheWithCheckedException("id", true);
fail("Should have failed");
}
catch (RuntimeException e) {
assertNotNull("missing original exception", e.getCause());
assertEquals(IOException.class, e.getCause().getClass());
}
catch (Exception e) {
fail("Wrong exception type " + e);
}
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
cs.cacheWithCheckedException("id", true))
.withCauseExactlyInstanceOf(IOException.class);
}

View File

@ -22,6 +22,7 @@ import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@ -156,14 +157,16 @@ public class SimpleMailMessageTests {
assertTrue(message1.equals(message2));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCopyCtorChokesOnNullOriginalMessage() throws Exception {
new SimpleMailMessage(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new SimpleMailMessage(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCopyToChokesOnNullTargetMessage() throws Exception {
new SimpleMailMessage().copyTo(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new SimpleMailMessage().copyTo(null));
}
}

View File

@ -18,6 +18,7 @@ package org.springframework.mail.javamail;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
/**
@ -69,9 +70,10 @@ public class InternetAddressEditorTests {
assertEquals("Whitespace was not stripped", SIMPLE, editor.getAsText());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void simpleBadAddress() {
editor.setAsText(BAD);
assertThatIllegalArgumentException().isThrownBy(() ->
editor.setAsText(BAD));
}
}

View File

@ -42,12 +42,12 @@ import org.springframework.mail.MailSendException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.util.ObjectUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.entry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@ -402,18 +402,9 @@ public class JavaMailSenderTests {
sender.setUsername("username");
sender.setPassword("password");
SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
try {
sender.send(simpleMessage1);
fail("Should have thrown MailSendException");
}
catch (MailSendException ex) {
// expected
ex.printStackTrace();
assertTrue(ex.getFailedMessages() != null);
assertEquals(1, ex.getFailedMessages().size());
assertSame(simpleMessage1, ex.getFailedMessages().keySet().iterator().next());
assertSame(ex.getCause(), ex.getFailedMessages().values().iterator().next());
}
assertThatExceptionOfType(MailSendException.class).isThrownBy(() ->
sender.send(simpleMessage1))
.satisfies(ex -> assertThat(ex.getFailedMessages()).containsExactly(entry(simpleMessage1, (Exception) ex.getCause())));
}
@Test
@ -423,16 +414,9 @@ public class JavaMailSenderTests {
sender.setUsername("username");
sender.setPassword("password");
SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
try {
sender.send(simpleMessage1);
fail("Should have thrown MailSendException");
}
catch (MailSendException ex) {
// expected
ex.printStackTrace();
assertTrue(ex.getFailedMessages() != null);
assertEquals(0, ex.getFailedMessages().size());
}
assertThatExceptionOfType(MailSendException.class).isThrownBy(() ->
sender.send(simpleMessage1))
.satisfies(ex -> assertThat(ex.getFailedMessages()).isEmpty());
}
@Test

View File

@ -41,6 +41,7 @@ import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup;
import org.springframework.tests.sample.beans.TestBean;
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.assertNotSame;
@ -131,11 +132,12 @@ public class QuartzSupportTests {
bean.destroy();
}
@Test(expected = IllegalArgumentException.class)
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void jobDetailWithRunnableInsteadOfJob() {
JobDetailImpl jobDetail = new JobDetailImpl();
jobDetail.setJobClass((Class) DummyRunnable.class);
assertThatIllegalArgumentException().isThrownBy(() ->
jobDetail.setJobClass((Class) DummyRunnable.class));
}
@Test

View File

@ -29,9 +29,9 @@ import org.springframework.context.support.GenericApplicationContext;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.validation.beanvalidation.BeanValidationPostProcessor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@ -44,14 +44,9 @@ public class BeanValidationPostProcessorTests {
ac.registerBeanDefinition("bvpp", new RootBeanDefinition(BeanValidationPostProcessor.class));
ac.registerBeanDefinition("capp", new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class));
ac.registerBeanDefinition("bean", new RootBeanDefinition(NotNullConstrainedBean.class));
try {
ac.refresh();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.getRootCause().getMessage().contains("testBean"));
assertTrue(ex.getRootCause().getMessage().contains("invalid"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
ac::refresh)
.satisfies(ex -> assertThat(ex.getRootCause().getMessage()).contains("testBean", "invalid"));
ac.close();
}
@ -87,14 +82,9 @@ public class BeanValidationPostProcessorTests {
bd.getPropertyValues().add("testBean", new TestBean());
bd.getPropertyValues().add("stringValue", "s");
ac.registerBeanDefinition("bean", bd);
try {
ac.refresh();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.getRootCause().getMessage().contains("stringValue"));
assertTrue(ex.getRootCause().getMessage().contains("invalid"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
ac::refresh)
.satisfies(ex -> assertThat(ex.getRootCause().getMessage()).contains("stringValue", "invalid"));
ac.close();
}

View File

@ -18,6 +18,7 @@ package org.springframework.validation.beanvalidation2;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
@ -41,9 +42,9 @@ import org.springframework.validation.beanvalidation.CustomValidatorBean;
import org.springframework.validation.beanvalidation.MethodValidationInterceptor;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@ -76,52 +77,20 @@ public class MethodValidationTests {
private void doTestProxyValidation(MyValidInterface<String> proxy) {
assertNotNull(proxy.myValidMethod("value", 5));
try {
assertNotNull(proxy.myValidMethod("value", 15));
fail("Should have thrown ValidationException");
}
catch (javax.validation.ValidationException ex) {
// expected
}
try {
assertNotNull(proxy.myValidMethod(null, 5));
fail("Should have thrown ValidationException");
}
catch (javax.validation.ValidationException ex) {
// expected
}
try {
assertNotNull(proxy.myValidMethod("value", 0));
fail("Should have thrown ValidationException");
}
catch (javax.validation.ValidationException ex) {
// expected
}
assertThatExceptionOfType(ValidationException.class).isThrownBy(() ->
proxy.myValidMethod("value", 15));
assertThatExceptionOfType(ValidationException.class).isThrownBy(() ->
proxy.myValidMethod(null, 5));
assertThatExceptionOfType(ValidationException.class).isThrownBy(() ->
proxy.myValidMethod("value", 0));
proxy.myValidAsyncMethod("value", 5);
try {
proxy.myValidAsyncMethod("value", 15);
fail("Should have thrown ValidationException");
}
catch (javax.validation.ValidationException ex) {
// expected
}
try {
proxy.myValidAsyncMethod(null, 5);
fail("Should have thrown ValidationException");
}
catch (javax.validation.ValidationException ex) {
// expected
}
assertThatExceptionOfType(ValidationException.class).isThrownBy(() ->
proxy.myValidAsyncMethod("value", 15));
assertThatExceptionOfType(ValidationException.class).isThrownBy(() ->
proxy.myValidAsyncMethod(null, 5));
assertEquals("myValue", proxy.myGenericMethod("myValue"));
try {
proxy.myGenericMethod(null);
fail("Should have thrown ValidationException");
}
catch (javax.validation.ValidationException ex) {
// expected
}
assertThatExceptionOfType(ValidationException.class).isThrownBy(() ->
proxy.myGenericMethod(null));
}
@Test

View File

@ -52,13 +52,13 @@ import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@ -77,12 +77,8 @@ public class ValidatorFactoryTests {
assertEquals(2, result.size());
for (ConstraintViolation<ValidPerson> cv : result) {
String path = cv.getPropertyPath().toString();
if ("name".equals(path) || "address.street".equals(path)) {
assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NotNull);
}
else {
fail("Invalid constraint violation with path '" + path + "'");
}
assertThat(path).matches(actual -> "name".equals(actual) || "address.street".equals(actual));
assertThat(cv.getConstraintDescriptor().getAnnotation()).isInstanceOf(NotNull.class);
}
Validator nativeValidator = validator.unwrap(Validator.class);
@ -105,12 +101,8 @@ public class ValidatorFactoryTests {
assertEquals(2, result.size());
for (ConstraintViolation<ValidPerson> cv : result) {
String path = cv.getPropertyPath().toString();
if ("name".equals(path) || "address.street".equals(path)) {
assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NotNull);
}
else {
fail("Invalid constraint violation with path '" + path + "'");
}
assertThat(path).matches(actual -> "name".equals(actual) || "address.street".equals(actual));
assertThat(cv.getConstraintDescriptor().getAnnotation()).isInstanceOf(NotNull.class);
}
Validator nativeValidator = validator.unwrap(Validator.class);

View File

@ -23,6 +23,7 @@ import org.springframework.aop.aspectj.AfterThrowingAdviceBindingTestAspect.Afte
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.tests.sample.beans.ITestBean;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@ -54,44 +55,50 @@ public class AfterThrowingAdviceBindingTests {
}
@Test(expected = Throwable.class)
@Test
public void testSimpleAfterThrowing() throws Throwable {
this.testBean.exceptional(new Throwable());
assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
this.testBean.exceptional(new Throwable()));
verify(mockCollaborator).noArgs();
}
@Test(expected = Throwable.class)
@Test
public void testAfterThrowingWithBinding() throws Throwable {
Throwable t = new Throwable();
this.testBean.exceptional(t);
assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
this.testBean.exceptional(t));
verify(mockCollaborator).oneThrowable(t);
}
@Test(expected = Throwable.class)
@Test
public void testAfterThrowingWithNamedTypeRestriction() throws Throwable {
Throwable t = new Throwable();
this.testBean.exceptional(t);
assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
this.testBean.exceptional(t));
verify(mockCollaborator).noArgs();
verify(mockCollaborator).oneThrowable(t);
verify(mockCollaborator).noArgsOnThrowableMatch();
}
@Test(expected = Throwable.class)
@Test
public void testAfterThrowingWithRuntimeExceptionBinding() throws Throwable {
RuntimeException ex = new RuntimeException();
this.testBean.exceptional(ex);
assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
this.testBean.exceptional(ex));
verify(mockCollaborator).oneRuntimeException(ex);
}
@Test(expected = Throwable.class)
@Test
public void testAfterThrowingWithTypeSpecified() throws Throwable {
this.testBean.exceptional(new Throwable());
assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
this.testBean.exceptional(new Throwable()));
verify(mockCollaborator).noArgsOnThrowableMatch();
}
@Test(expected = Throwable.class)
@Test
public void testAfterThrowingWithRuntimeTypeSpecified() throws Throwable {
this.testBean.exceptional(new RuntimeException());
assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
this.testBean.exceptional(new RuntimeException()));
verify(mockCollaborator).noArgsOnRuntimeExceptionMatch();
}

View File

@ -29,8 +29,6 @@ import org.springframework.core.Ordered;
import org.springframework.lang.Nullable;
import org.springframework.tests.sample.beans.ITestBean;
import static org.junit.Assert.fail;
/**
* @author Adrian Colyer
* @author Chris Beams
@ -101,12 +99,12 @@ public class AspectAndAdvicePrecedenceTests {
private void checkAdvice(String whatJustHappened) {
//System.out.println("[" + adviceInvocationNumber + "] " + whatJustHappened + " ==> " + EXPECTED[adviceInvocationNumber]);
if (adviceInvocationNumber > (EXPECTED.length - 1)) {
fail("Too many advice invocations, expecting " + EXPECTED.length
throw new AssertionError("Too many advice invocations, expecting " + EXPECTED.length
+ " but had " + adviceInvocationNumber);
}
String expecting = EXPECTED[adviceInvocationNumber++];
if (!whatJustHappened.equals(expecting)) {
fail("Expecting '" + expecting + "' on advice invocation " + adviceInvocationNumber +
throw new AssertionError("Expecting '" + expecting + "' on advice invocation " + adviceInvocationNumber +
" but got '" + whatJustHappened + "'");
}
}

View File

@ -24,9 +24,9 @@ import org.springframework.aop.support.AopUtils;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.tests.sample.beans.ITestBean;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rod Johnson
@ -69,13 +69,8 @@ public class DeclareParentsTests {
testBeanProxy.setName("");
lockable.lock();
try {
testBeanProxy.setName(" ");
fail("Should be locked");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().as("should be locked").isThrownBy(() ->
testBeanProxy.setName(" "));
}
}

View File

@ -26,8 +26,7 @@ import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Adrian Colyer
@ -44,14 +43,9 @@ public class SPR3064Tests {
new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());
service = (Service) ctx.getBean("service");
try {
this.service.serveMe();
fail("service operation has not been advised by transaction interceptor");
}
catch (RuntimeException ex) {
assertEquals("advice invoked",ex.getMessage());
}
assertThatExceptionOfType(RuntimeException.class).isThrownBy(
this.service::serveMe)
.withMessageContaining("advice invoked");
}
}

View File

@ -22,8 +22,7 @@ import org.xml.sax.SAXParseException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Adrian Colyer
@ -38,13 +37,9 @@ public class AopNamespaceHandlerAdviceTypeTests {
@Test
public void testParsingOfAdviceTypesWithError() {
try {
new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass());
fail("Expected BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
assertTrue(ex.contains(SAXParseException.class));
}
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass()))
.matches(ex -> ex.contains(SAXParseException.class));
}
}

View File

@ -21,8 +21,7 @@ import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Adrian Colyer
@ -37,13 +36,9 @@ public class AopNamespaceHandlerArgNamesTests {
@Test
public void testArgNamesError() {
try {
new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass());
fail("Expected BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.contains(IllegalArgumentException.class));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass()))
.matches(ex -> ex.contains(IllegalArgumentException.class));
}
}

View File

@ -22,8 +22,7 @@ import org.xml.sax.SAXParseException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Adrian Colyer
@ -38,13 +37,9 @@ public class AopNamespaceHandlerReturningTests {
@Test
public void testParseReturningOnOtherAdviceType() {
try {
new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass());
fail("Expected BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
assertTrue(ex.contains(SAXParseException.class));
}
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass()))
.matches(ex -> ex.contains(SAXParseException.class));
}
}

View File

@ -22,8 +22,7 @@ import org.xml.sax.SAXParseException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Adrian Colyer
@ -38,13 +37,9 @@ public class AopNamespaceHandlerThrowingTests {
@Test
public void testParseThrowingOnOtherAdviceType() {
try {
new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass());
fail("Expected BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
assertTrue(ex.contains(SAXParseException.class));
}
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-error.xml", getClass()))
.matches(ex -> ex.contains(SAXParseException.class));
}
}

View File

@ -23,6 +23,7 @@ import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
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;
@ -56,37 +57,42 @@ public class MethodLocatingFactoryBeanTests {
assertEquals(Method.class, factory.getObjectType());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithNullTargetBeanName() {
factory.setMethodName("toString()");
factory.setBeanFactory(beanFactory);
assertThatIllegalArgumentException().isThrownBy(() ->
factory.setBeanFactory(beanFactory));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithEmptyTargetBeanName() {
factory.setTargetBeanName("");
factory.setMethodName("toString()");
factory.setBeanFactory(beanFactory);
assertThatIllegalArgumentException().isThrownBy(() ->
factory.setBeanFactory(beanFactory));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithNullTargetMethodName() {
factory.setTargetBeanName(BEAN_NAME);
factory.setBeanFactory(beanFactory);
assertThatIllegalArgumentException().isThrownBy(() ->
factory.setBeanFactory(beanFactory));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithEmptyTargetMethodName() {
factory.setTargetBeanName(BEAN_NAME);
factory.setMethodName("");
factory.setBeanFactory(beanFactory);
assertThatIllegalArgumentException().isThrownBy(() ->
factory.setBeanFactory(beanFactory));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWhenTargetBeanClassCannotBeResolved() {
factory.setTargetBeanName(BEAN_NAME);
factory.setMethodName("toString()");
factory.setBeanFactory(beanFactory);
assertThatIllegalArgumentException().isThrownBy(() ->
factory.setBeanFactory(beanFactory));
verify(beanFactory).getType(BEAN_NAME);
}
@ -104,13 +110,14 @@ public class MethodLocatingFactoryBeanTests {
assertEquals("Bingo", method.invoke("Bingo"));
}
@Test(expected = IllegalArgumentException.class)
@Test
@SuppressWarnings("unchecked")
public void testWhereMethodCannotBeResolved() {
given(beanFactory.getType(BEAN_NAME)).willReturn((Class)String.class);
factory.setTargetBeanName(BEAN_NAME);
factory.setMethodName("loadOfOld()");
factory.setBeanFactory(beanFactory);
assertThatIllegalArgumentException().isThrownBy(() ->
factory.setBeanFactory(beanFactory));
}
}

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