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,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));
}
}

View File

@@ -76,6 +76,10 @@ import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.SerializationTestUtils;
import org.springframework.util.StopWatch;
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.assertNotNull;
@@ -83,7 +87,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 Rod Johnson
@@ -127,12 +130,14 @@ public abstract class AbstractAopProxyTests {
}
@Test(expected = AopConfigException.class)
@Test
public void testNoInterceptorsAndNoTarget() {
AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
// Add no interceptors
AopProxy aop = createAopProxy(pc);
aop.getProxy();
assertThatExceptionOfType(AopConfigException.class).isThrownBy(() -> {
AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
//Add no interceptors
AopProxy aop = createAopProxy(pc);
aop.getProxy();
});
}
/**
@@ -377,14 +382,15 @@ public abstract class AbstractAopProxyTests {
assertEquals("3 more invocations via AOP as the first call was reentrant through the proxy", 4, di.getCount());
}
@Test(expected = IllegalStateException.class)
@Test
// Should fail to get proxy as exposeProxy wasn't set to true
public void testTargetCantGetProxyByDefault() {
NeedsToSeeProxy et = new NeedsToSeeProxy();
ProxyFactory pf1 = new ProxyFactory(et);
assertFalse(pf1.isExposeProxy());
INeedsToSeeProxy proxied = (INeedsToSeeProxy) createProxy(pf1);
proxied.incrementViaProxy();
assertThatIllegalStateException().isThrownBy(() ->
proxied.incrementViaProxy());
}
@Test
@@ -468,15 +474,11 @@ public abstract class AbstractAopProxyTests {
pc.setTargetSource(mockTargetSource);
AopProxy aop = createAopProxy(pc);
try {
ITestBean tb = (ITestBean) aop.getProxy();
// Note: exception param below isn't used
tb.exceptional(expectedException);
fail("Should have thrown exception raised by interceptor");
}
catch (Exception thrown) {
assertEquals("exception matches", expectedException, thrown);
}
assertThatExceptionOfType(Exception.class).isThrownBy(() -> {
ITestBean tb = (ITestBean) aop.getProxy();
// Note: exception param below isn't used
tb.exceptional(expectedException);
}).matches(expectedException::equals);
}
/**
@@ -503,18 +505,9 @@ public abstract class AbstractAopProxyTests {
AopProxy aop = createAopProxy(pc);
ITestBean tb = (ITestBean) aop.getProxy();
try {
// Note: exception param below isn't used
tb.getAge();
fail("Should have wrapped exception raised by interceptor");
}
catch (UndeclaredThrowableException thrown) {
assertEquals("exception matches", unexpectedException, thrown.getUndeclaredThrowable());
}
catch (Exception ex) {
ex.printStackTrace();
fail("Didn't expect exception: " + ex);
}
assertThatExceptionOfType(UndeclaredThrowableException.class).isThrownBy(
tb::getAge)
.satisfies(ex -> assertThat(ex.getUndeclaredThrowable()).isEqualTo(unexpectedException));
}
@Test
@@ -536,14 +529,9 @@ public abstract class AbstractAopProxyTests {
AopProxy aop = createAopProxy(pc);
ITestBean tb = (ITestBean) aop.getProxy();
try {
// Note: exception param below isn't used
tb.getAge();
fail("Should have wrapped exception raised by interceptor");
}
catch (RuntimeException thrown) {
assertEquals("exception matches", unexpectedException, thrown);
}
assertThatExceptionOfType(RuntimeException.class).isThrownBy(
tb::getAge)
.matches(unexpectedException::equals);
}
/**
@@ -591,13 +579,8 @@ public abstract class AbstractAopProxyTests {
* Throw an exception if there is an Invocation.
*/
private void assertNoInvocationContext() {
try {
ExposeInvocationInterceptor.currentInvocation();
fail("Expected no invocation context");
}
catch (IllegalStateException ex) {
// ok
}
assertThatIllegalStateException().isThrownBy(
ExposeInvocationInterceptor::currentInvocation);
}
/**
@@ -637,13 +620,8 @@ public abstract class AbstractAopProxyTests {
lockable.lock();
assertEquals(newAge, itb.getAge());
try {
itb.setAge(1);
fail("Setters should fail when locked");
}
catch (LockedException ex) {
// ok
}
assertThatExceptionOfType(LockedException.class).isThrownBy(() ->
itb.setAge(1));
assertEquals(newAge, itb.getAge());
// Unlock
@@ -737,13 +715,9 @@ public abstract class AbstractAopProxyTests {
TestBean target = new TestBean();
target.setAge(21);
ProxyFactory pc = new ProxyFactory(target);
try {
pc.addAdvice(new DummyIntroductionAdviceImpl());
fail("Shouldn't be able to add introduction interceptor except via introduction advice");
}
catch (AopConfigException ex) {
assertTrue(ex.getMessage().contains("ntroduction"));
}
assertThatExceptionOfType(AopConfigException.class).isThrownBy(() ->
pc.addAdvice(new DummyIntroductionAdviceImpl()))
.withMessageContaining("ntroduction");
// Check it still works: proxy factory state shouldn't have been corrupted
ITestBean proxied = (ITestBean) createProxy(pc);
assertEquals(target.getAge(), proxied.getAge());
@@ -755,18 +729,15 @@ public abstract class AbstractAopProxyTests {
target.setAge(21);
ProxyFactory pc = new ProxyFactory(target);
pc.addAdvisor(new DefaultIntroductionAdvisor(new DummyIntroductionAdviceImpl(), Comparable.class));
try {
assertThatExceptionOfType(Exception.class).isThrownBy(() -> {
// TODO May fail on either call: may want to tighten up definition
ITestBean proxied = (ITestBean) createProxy(pc);
proxied.getName();
fail("Bogus introduction");
}
catch (Exception ex) {
// TODO used to catch UnknownAdviceTypeException, but
// with CGLIB some errors are in proxy creation and are wrapped
// in aspect exception. Error message is still fine.
//assertTrue(ex.getMessage().indexOf("ntroduction") > -1);
}
});
// TODO used to catch UnknownAdviceTypeException, but
// with CGLIB some errors are in proxy creation and are wrapped
// in aspect exception. Error message is still fine.
//assertTrue(ex.getMessage().indexOf("ntroduction") > -1);
}
/**
@@ -778,13 +749,8 @@ public abstract class AbstractAopProxyTests {
TestBean target = new TestBean();
target.setAge(21);
ProxyFactory pc = new ProxyFactory(target);
try {
pc.addAdvisor(0, new DefaultIntroductionAdvisor(new TimestampIntroductionInterceptor(), ITestBean.class));
fail("Shouldn't be able to add introduction advice introducing an unimplemented interface");
}
catch (IllegalArgumentException ex) {
//assertTrue(ex.getMessage().indexOf("ntroduction") > -1);
}
assertThatIllegalArgumentException().isThrownBy(() ->
pc.addAdvisor(0, new DefaultIntroductionAdvisor(new TimestampIntroductionInterceptor(), ITestBean.class)));
// Check it still works: proxy factory state shouldn't have been corrupted
ITestBean proxied = (ITestBean) createProxy(pc);
assertEquals(target.getAge(), proxied.getAge());
@@ -813,12 +779,8 @@ public abstract class AbstractAopProxyTests {
pc.addAdvisor(new DefaultIntroductionAdvisor(new MyDi()));
TimeStamped ts = (TimeStamped) createProxy(pc);
try {
ts.getTimeStamp();
fail("Should throw UnsupportedOperationException");
}
catch (UnsupportedOperationException ex) {
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(
ts::getTimeStamp);
}
/**
@@ -829,13 +791,9 @@ public abstract class AbstractAopProxyTests {
TestBean target = new TestBean();
target.setAge(21);
ProxyFactory pc = new ProxyFactory(target);
try {
pc.addAdvisor(0, new DefaultIntroductionAdvisor(new TimestampIntroductionInterceptor(), TestBean.class));
fail("Shouldn't be able to add introduction advice that introduces a class, rather than an interface");
}
catch (IllegalArgumentException ex) {
assertTrue(ex.getMessage().contains("interface"));
}
assertThatIllegalArgumentException().as("Shouldn't be able to add introduction advice that introduces a class, rather than an interface").isThrownBy(() ->
pc.addAdvisor(0, new DefaultIntroductionAdvisor(new TimestampIntroductionInterceptor(), TestBean.class)))
.withMessageContaining("interface");
// Check it still works: proxy factory state shouldn't have been corrupted
ITestBean proxied = (ITestBean) createProxy(pc);
assertEquals(target.getAge(), proxied.getAge());
@@ -850,13 +808,9 @@ public abstract class AbstractAopProxyTests {
pc.addAdvice(new NopInterceptor());
ITestBean proxied = (ITestBean) createProxy(pc);
pc.setFrozen(true);
try {
pc.addAdvice(0, new NopInterceptor());
fail("Shouldn't be able to add interceptor when frozen");
}
catch (AopConfigException ex) {
assertTrue(ex.getMessage().contains("frozen"));
}
assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to add interceptor when frozen").isThrownBy(() ->
pc.addAdvice(0, new NopInterceptor()))
.withMessageContaining("frozen");
// Check it still works: proxy factory state shouldn't have been corrupted
assertEquals(target.getAge(), proxied.getAge());
assertEquals(1, ((Advised) proxied).getAdvisors().length);
@@ -877,13 +831,9 @@ public abstract class AbstractAopProxyTests {
Advised advised = (Advised) proxied;
assertTrue(pc.isFrozen());
try {
advised.addAdvisor(new DefaultPointcutAdvisor(new NopInterceptor()));
fail("Shouldn't be able to add Advisor when frozen");
}
catch (AopConfigException ex) {
assertTrue(ex.getMessage().contains("frozen"));
}
assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to add Advisor when frozen").isThrownBy(() ->
advised.addAdvisor(new DefaultPointcutAdvisor(new NopInterceptor())))
.withMessageContaining("frozen");
// Check it still works: proxy factory state shouldn't have been corrupted
assertEquals(target.getAge(), proxied.getAge());
assertEquals(1, advised.getAdvisors().length);
@@ -901,13 +851,9 @@ public abstract class AbstractAopProxyTests {
Advised advised = (Advised) proxied;
assertTrue(pc.isFrozen());
try {
advised.removeAdvisor(0);
fail("Shouldn't be able to remove Advisor when frozen");
}
catch (AopConfigException ex) {
assertTrue(ex.getMessage().contains("frozen"));
}
assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to remove Advisor when frozen").isThrownBy(() ->
advised.removeAdvisor(0))
.withMessageContaining("frozen");
// Didn't get removed
assertEquals(1, advised.getAdvisors().length);
pc.setFrozen(false);
@@ -1424,13 +1370,8 @@ public abstract class AbstractAopProxyTests {
assertEquals(2, cca.getCalls());
assertEquals(26, proxied.getAge());
assertEquals(4, cca.getCalls());
try {
proxied.exceptional(new SpecializedUncheckedException("foo", (SQLException)null));
fail("Should have thrown CannotGetJdbcConnectionException");
}
catch (SpecializedUncheckedException ex) {
// expected
}
assertThatExceptionOfType(SpecializedUncheckedException.class).as("Should have thrown CannotGetJdbcConnectionException").isThrownBy(() ->
proxied.exceptional(new SpecializedUncheckedException("foo", (SQLException)null)));
assertEquals(6, cca.getCalls());
}
@@ -1463,13 +1404,9 @@ public abstract class AbstractAopProxyTests {
assertEquals(1, nop1.getCount());
assertEquals(1, nop2.getCount());
// Will fail, after invoking Nop1
try {
proxied.setAge(26);
fail("before advice should have ended chain");
}
catch (RuntimeException ex) {
assertEquals(rex, ex);
}
assertThatExceptionOfType(RuntimeException.class).as("before advice should have ended chain").isThrownBy(() ->
proxied.setAge(26))
.matches(rex::equals);
assertEquals(2, ba.getCalls());
assertEquals(2, nop1.getCount());
// Nop2 didn't get invoked when the exception was thrown
@@ -1532,13 +1469,9 @@ public abstract class AbstractAopProxyTests {
assertEquals(2, car.getCalls());
Exception exc = new Exception();
// On exception it won't be invoked
try {
proxied.exceptional(exc);
fail();
}
catch (Throwable t) {
assertSame(exc, t);
}
assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
proxied.exceptional(exc))
.satisfies(ex -> assertThat(ex).isSameAs(exc));
assertEquals(2, car.getCalls());
}
@@ -1567,22 +1500,13 @@ public abstract class AbstractAopProxyTests {
assertEquals(0, th.getCalls());
Exception ex = new Exception();
// Will be advised but doesn't match
try {
proxied.echoException(1, ex);
fail();
}
catch (Exception caught) {
assertEquals(ex, caught);
}
ex = new FileNotFoundException();
try {
proxied.echoException(1, ex);
fail();
}
catch (FileNotFoundException caught) {
assertEquals(ex, caught);
}
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
proxied.echoException(1, ex))
.matches(ex::equals);
FileNotFoundException fex = new FileNotFoundException();
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() ->
proxied.echoException(1, fex))
.matches(fex::equals);
assertEquals(1, th.getCalls("ioException"));
}
@@ -1602,23 +1526,16 @@ public abstract class AbstractAopProxyTests {
assertEquals(0, th.getCalls());
Exception ex = new Exception();
// Will be advised but doesn't match
try {
proxied.echoException(1, ex);
fail();
}
catch (Exception caught) {
assertEquals(ex, caught);
}
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
proxied.echoException(1, ex))
.matches(ex::equals);
// Subclass of RemoteException
ex = new MarshalException("");
try {
proxied.echoException(1, ex);
fail();
}
catch (MarshalException caught) {
assertEquals(ex, caught);
}
MarshalException mex = new MarshalException("");
assertThatExceptionOfType(MarshalException.class).isThrownBy(() ->
proxied.echoException(1, mex))
.matches(mex::equals);
assertEquals(1, th.getCalls("remoteException"));
}

View File

@@ -36,6 +36,8 @@ import org.springframework.tests.aop.interceptor.NopInterceptor;
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.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
@@ -79,17 +81,19 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testNullConfig() {
new CglibAopProxy(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new CglibAopProxy(null));
}
@Test(expected = AopConfigException.class)
@Test
public void testNoTarget() {
AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
pc.addAdvice(new NopInterceptor());
AopProxy aop = createAopProxy(pc);
aop.getProxy();
assertThatExceptionOfType(AopConfigException.class).isThrownBy(
aop::getProxy);
}
@Test

View File

@@ -28,6 +28,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.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
@@ -56,9 +57,10 @@ public class JdkDynamicProxyTests extends AbstractAopProxyTests implements Seria
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testNullConfig() {
new JdkDynamicAopProxy(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new JdkDynamicAopProxy(null));
}
@Test

View File

@@ -17,7 +17,6 @@
package org.springframework.aop.framework;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.LinkedList;
@@ -61,6 +60,9 @@ import org.springframework.tests.sample.beans.SideEffectBean;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.SerializationTestUtils;
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.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -70,7 +72,6 @@ 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;
/**
* @since 13.03.2003
@@ -144,32 +145,22 @@ public class ProxyFactoryBeanTests {
}
private void testDoubleTargetSourceIsRejected(String name) {
try {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(DBL_TARGETSOURCE_CONTEXT, CLASS));
bf.getBean(name);
fail("Should not allow TargetSource to be specified in interceptorNames as well as targetSource property");
}
catch (BeanCreationException ex) {
// Root cause of the problem must be an AOP exception
AopConfigException aex = (AopConfigException) ex.getCause();
assertTrue(aex.getMessage().contains("TargetSource"));
}
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(DBL_TARGETSOURCE_CONTEXT, CLASS));
assertThatExceptionOfType(BeanCreationException.class).as("Should not allow TargetSource to be specified in interceptorNames as well as targetSource property").isThrownBy(() ->
bf.getBean(name))
.withCauseInstanceOf(AopConfigException.class)
.satisfies(ex -> assertThat(ex.getCause().getMessage()).contains("TargetSource"));
}
@Test
public void testTargetSourceNotAtEndOfInterceptorNamesIsRejected() {
try {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(NOTLAST_TARGETSOURCE_CONTEXT, CLASS));
bf.getBean("targetSourceNotLast");
fail("TargetSource or non-advised object must be last in interceptorNames");
}
catch (BeanCreationException ex) {
// Root cause of the problem must be an AOP exception
AopConfigException aex = (AopConfigException) ex.getCause();
assertTrue(aex.getMessage().contains("interceptorNames"));
}
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(NOTLAST_TARGETSOURCE_CONTEXT, CLASS));
assertThatExceptionOfType(BeanCreationException.class).as("TargetSource or non-advised object must be last in interceptorNames").isThrownBy(() ->
bf.getBean("targetSourceNotLast"))
.withCauseInstanceOf(AopConfigException.class)
.satisfies(ex -> assertThat(ex.getCause().getMessage()).contains("interceptorNames"));
}
@Test
@@ -205,13 +196,9 @@ public class ProxyFactoryBeanTests {
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(TARGETSOURCE_CONTEXT, CLASS));
ITestBean tb = (ITestBean) bf.getBean("noTarget");
try {
tb.getName();
fail();
}
catch (UnsupportedOperationException ex) {
assertEquals("getName", ex.getMessage());
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
tb.getName())
.withMessage("getName");
FactoryBean<?> pfb = (ProxyFactoryBean) bf.getBean("&noTarget");
assertTrue("Has correct object type", ITestBean.class.isAssignableFrom(pfb.getObjectType()));
}
@@ -332,15 +319,10 @@ public class ProxyFactoryBeanTests {
});
assertEquals("Have correct advisor count", 2, config.getAdvisors().length);
tb = (ITestBean) factory.getBean("test1");
try {
// Will fail now
tb.toString();
fail("Evil interceptor added programmatically should fail all method calls");
}
catch (Exception thrown) {
assertTrue(thrown == ex);
}
ITestBean tb1 = (ITestBean) factory.getBean("test1");
assertThatExceptionOfType(Exception.class).isThrownBy(
tb1::toString)
.satisfies(thrown -> assertThat(thrown).isSameAs(ex));
}
/**
@@ -466,25 +448,18 @@ public class ProxyFactoryBeanTests {
assertEquals(2, cba.getCalls());
assertEquals(0, th.getCalls());
Exception expected = new Exception();
try {
echo.echoException(1, expected);
fail();
}
catch (Exception ex) {
assertEquals(expected, ex);
}
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
echo.echoException(1, expected))
.matches(expected::equals);
// No throws handler method: count should still be 0
assertEquals(0, th.getCalls());
// Handler knows how to handle this exception
expected = new FileNotFoundException();
try {
echo.echoException(1, expected);
fail();
}
catch (IOException ex) {
assertEquals(expected, ex);
}
FileNotFoundException expectedFileNotFound = new FileNotFoundException();
assertThatIOException().isThrownBy(() ->
echo.echoException(1, expectedFileNotFound))
.matches(expectedFileNotFound::equals);
// One match
assertEquals(1, th.getCalls("ioException"));
}
@@ -494,13 +469,8 @@ public class ProxyFactoryBeanTests {
/*
@Test
public void testNoInterceptorNamesWithoutTarget() {
try {
ITestBean tb = (ITestBean) factory.getBean("noInterceptorNamesWithoutTarget");
fail("Should require interceptor names");
}
catch (AopConfigException ex) {
// Ok
}
assertThatExceptionOfType(AopConfigurationException.class).as("Should require interceptor names").isThrownBy(() ->
ITestBean tb = (ITestBean) factory.getBean("noInterceptorNamesWithoutTarget"));
}
@Test
@@ -513,13 +483,8 @@ public class ProxyFactoryBeanTests {
public void testEmptyInterceptorNames() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(INVALID_CONTEXT, CLASS));
try {
bf.getBean("emptyInterceptorNames");
fail("Interceptor names cannot be empty");
}
catch (BeanCreationException ex) {
// Ok
}
assertThatExceptionOfType(BeanCreationException.class).as("Interceptor names cannot be empty").isThrownBy(() ->
bf.getBean("emptyInterceptorNames"));
}
/**
@@ -529,13 +494,9 @@ public class ProxyFactoryBeanTests {
public void testGlobalsWithoutTarget() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(INVALID_CONTEXT, CLASS));
try {
bf.getBean("globalsWithoutTarget");
fail("Should require target name");
}
catch (BeanCreationException ex) {
assertTrue(ex.getCause() instanceof AopConfigException);
}
assertThatExceptionOfType(BeanCreationException.class).as("Should require target name").isThrownBy(() ->
bf.getBean("globalsWithoutTarget"))
.withCauseInstanceOf(AopConfigException.class);
}
/**
@@ -559,12 +520,8 @@ public class ProxyFactoryBeanTests {
agi = (AddedGlobalInterface) l;
assertTrue(agi.globalsAdded() == -1);
try {
agi = (AddedGlobalInterface) factory.getBean("test1");
fail("Aspect interface should't be implemeneted without globals");
}
catch (ClassCastException ex) {
}
assertThat(factory.getBean("test1")).as("Aspect interface should't be implemeneted without globals")
.isNotInstanceOf(AddedGlobalInterface.class);
}
@Test
@@ -639,20 +596,10 @@ public class ProxyFactoryBeanTests {
((Lockable) bean1).lock();
try {
bean1.setAge(5);
fail("expected LockedException");
}
catch (LockedException ex) {
// expected
}
assertThatExceptionOfType(LockedException.class).isThrownBy(() ->
bean1.setAge(5));
try {
bean2.setAge(6);
}
catch (LockedException ex) {
fail("did not expect LockedException");
}
bean2.setAge(6); //do not expect LockedException"
}
@Test
@@ -670,20 +617,11 @@ public class ProxyFactoryBeanTests {
((Lockable) bean1).lock();
try {
bean1.setAge(5);
fail("expected LockedException");
}
catch (LockedException ex) {
// expected
}
assertThatExceptionOfType(LockedException.class).isThrownBy(() ->
bean1.setAge(5));
try {
bean2.setAge(6);
}
catch (LockedException ex) {
fail("did not expect LockedException");
}
// do not expect LockedException
bean2.setAge(6);
}
/**

View File

@@ -31,8 +31,8 @@ import org.springframework.aop.framework.Advised;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.tests.sample.beans.ITestBean;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* TestCase for AdvisorAdapterRegistrationManager mechanism.
@@ -54,14 +54,9 @@ public class AdvisorAdapterRegistrationTests {
new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-without-bpp.xml", getClass());
ITestBean tb = (ITestBean) ctx.getBean("testBean");
// just invoke any method to see if advice fired
try {
tb.getName();
fail("Should throw UnknownAdviceTypeException");
}
catch (UnknownAdviceTypeException ex) {
// expected
assertEquals(0, getAdviceImpl(tb).getInvocationCounter());
}
assertThatExceptionOfType(UnknownAdviceTypeException.class).isThrownBy(
tb::getName);
assertThat(getAdviceImpl(tb).getInvocationCounter()).isZero();
}
@Test
@@ -70,13 +65,8 @@ public class AdvisorAdapterRegistrationTests {
new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-with-bpp.xml", getClass());
ITestBean tb = (ITestBean) ctx.getBean("testBean");
// just invoke any method to see if advice fired
try {
tb.getName();
assertEquals(1, getAdviceImpl(tb).getInvocationCounter());
}
catch (UnknownAdviceTypeException ex) {
fail("Should not throw UnknownAdviceTypeException");
}
tb.getName();
getAdviceImpl(tb).getInvocationCounter();
}
private SimpleBeforeAdviceImpl getAdviceImpl(ITestBean tb) {

View File

@@ -25,6 +25,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.lang.Nullable;
import org.springframework.tests.sample.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
/**
@@ -34,14 +35,15 @@ import static org.junit.Assert.assertEquals;
*/
public class BeanNameAutoProxyCreatorInitTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testIgnoreAdvisorThatIsCurrentlyInCreation() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());
TestBean bean = (TestBean) ctx.getBean("bean");
bean.setName("foo");
assertEquals("foo", bean.getName());
bean.setName(null); // should throw
assertThatIllegalArgumentException().isThrownBy(() ->
bean.setName(null));
}
}

View File

@@ -32,10 +32,10 @@ import org.springframework.tests.aop.interceptor.NopInterceptor;
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;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rod Johnson
@@ -106,13 +106,8 @@ public class BeanNameAutoProxyCreatorTests {
// Can still mod second object
tb2.setAge(12);
// But can't mod first
try {
tb.setAge(6);
fail("Mixin should have locked this object");
}
catch (LockedException ex) {
// Ok
}
assertThatExceptionOfType(LockedException.class).as("mixin should have locked this object").isThrownBy(() ->
tb.setAge(6));
}
@Test
@@ -144,13 +139,8 @@ public class BeanNameAutoProxyCreatorTests {
// Can still mod second object
tb2.setAge(12);
// But can't mod first
try {
tb.setAge(6);
fail("Mixin should have locked this object");
}
catch (LockedException ex) {
// Ok
}
assertThatExceptionOfType(LockedException.class).as("mixin should have locked this object").isThrownBy(() ->
tb.setAge(6));
}
@Test

View File

@@ -32,10 +32,10 @@ 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.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 pooling invoker interceptor.
@@ -151,13 +151,8 @@ public class CommonsPool2TargetSourceTests {
}
// should be at maximum now
try {
targetSource.getTarget();
fail("Should throw NoSuchElementException");
}
catch (NoSuchElementException ex) {
// desired
}
assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(
targetSource::getTarget);
// lets now release an object and try to acquire a new one
targetSource.releaseTarget(pooledInstances[9]);
@@ -184,13 +179,8 @@ public class CommonsPool2TargetSourceTests {
}
// should be at maximum now
try {
targetSource.getTarget();
fail("Should throw NoSuchElementException");
}
catch (NoSuchElementException ex) {
// desired
}
assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(
targetSource::getTarget);
// lets now release an object and try to acquire a new one
targetSource.releaseTarget(pooledInstances[9]);

View File

@@ -35,9 +35,9 @@ import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.support.GenericApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Integration tests for handling JSR-303 {@link javax.inject.Qualifier} annotations.
@@ -62,14 +62,12 @@ public class InjectAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedFieldTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.satisfies(ex -> {
assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class);
assertThat(ex.getBeanName()).isEqualTo("autowired");
});
}
@Test
@@ -82,14 +80,12 @@ public class InjectAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedMethodParameterTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.satisfies(ex -> {
assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class);
assertThat(ex.getBeanName()).isEqualTo("autowired");
});
}
@Test
@@ -102,14 +98,9 @@ public class InjectAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedConstructorArgumentTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e instanceof UnsatisfiedDependencyException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
context::refresh)
.satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("autowired"));
}
@Test
@@ -212,14 +203,12 @@ public class InjectAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedFieldTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.satisfies(ex -> {
assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class);
assertThat(ex.getBeanName()).isEqualTo("autowired");
});
}
@Test
@@ -236,14 +225,12 @@ public class InjectAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedMethodParameterTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.satisfies(ex -> {
assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class);
assertThat(ex.getBeanName()).isEqualTo("autowired");
});
}
@Test
@@ -260,14 +247,9 @@ public class InjectAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedConstructorArgumentTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e instanceof UnsatisfiedDependencyException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
context::refresh)
.satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("autowired"));
}
@Test
@@ -370,14 +352,12 @@ public class InjectAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedFieldWithDefaultValueTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.satisfies(ex -> {
assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class);
assertThat(ex.getBeanName()).isEqualTo("autowired");
});
}
@Test
@@ -449,14 +429,12 @@ public class InjectAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedFieldWithMultipleAttributesTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.satisfies(ex -> {
assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class);
assertThat(ex.getBeanName()).isEqualTo("autowired");
});
}
@Test
@@ -507,14 +485,12 @@ public class InjectAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedFieldWithMultipleAttributesTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.satisfies(ex -> {
assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class);
assertThat(ex.getBeanName()).isEqualTo("autowired");
});
}
@Test
@@ -533,14 +509,9 @@ public class InjectAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedConstructorArgumentWithBaseQualifierNonDefaultValueTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e instanceof UnsatisfiedDependencyException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
context::refresh)
.satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("autowired"));
}

View File

@@ -34,9 +34,9 @@ import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.support.GenericApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Integration tests for handling {@link Qualifier} annotations.
@@ -63,14 +63,13 @@ public class QualifierAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedFieldTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.satisfies(ex -> {
assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class);
assertThat(ex.getBeanName()).isEqualTo("autowired");
});
}
@Test
@@ -83,14 +82,13 @@ public class QualifierAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedMethodParameterTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.satisfies(ex -> {
assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class);
assertThat(ex.getBeanName()).isEqualTo("autowired");
});
}
@Test
@@ -103,14 +101,9 @@ public class QualifierAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedConstructorArgumentTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e instanceof UnsatisfiedDependencyException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
context::refresh)
.satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("autowired"));
}
@Test
@@ -213,14 +206,12 @@ public class QualifierAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedFieldTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.satisfies(ex -> {
assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class);
assertThat(ex.getBeanName()).isEqualTo("autowired");
});
}
@Test
@@ -237,14 +228,12 @@ public class QualifierAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedMethodParameterTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.satisfies(ex -> {
assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class);
assertThat(ex.getBeanName()).isEqualTo("autowired");
});
}
@Test
@@ -261,14 +250,9 @@ public class QualifierAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedConstructorArgumentTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e instanceof UnsatisfiedDependencyException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
context::refresh)
.satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("autowired"));
}
@Test
@@ -391,14 +375,12 @@ public class QualifierAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedFieldWithDefaultValueTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.satisfies(ex -> {
assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class);
assertThat(ex.getBeanName()).isEqualTo("autowired");
});
}
@Test
@@ -470,14 +452,12 @@ public class QualifierAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedFieldWithMultipleAttributesTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.satisfies(ex -> {
assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class);
assertThat(ex.getBeanName()).isEqualTo("autowired");
});
}
@Test
@@ -528,14 +508,12 @@ public class QualifierAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedFieldWithMultipleAttributesTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getRootCause() instanceof NoSuchBeanDefinitionException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.satisfies(ex -> {
assertThat(ex.getRootCause()).isInstanceOf(NoSuchBeanDefinitionException.class);
assertThat(ex.getBeanName()).isEqualTo("autowired");
});
}
@Test
@@ -597,14 +575,9 @@ public class QualifierAnnotationAutowireContextTests {
context.registerBeanDefinition("autowired",
new RootBeanDefinition(QualifiedConstructorArgumentWithBaseQualifierNonDefaultValueTestBean.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
try {
context.refresh();
fail("expected BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e instanceof UnsatisfiedDependencyException);
assertEquals("autowired", e.getBeanName());
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
context::refresh)
.satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("autowired"));
}

View File

@@ -35,10 +35,10 @@ import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.support.StaticApplicationContext;
import static java.lang.String.format;
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;
import static org.springframework.util.ClassUtils.convertClassNameToResourcePath;
/**
@@ -59,13 +59,9 @@ public class QualifierAnnotationTests {
BeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
reader.loadBeanDefinitions(CONFIG_LOCATION);
context.registerSingleton("testBean", NonQualifiedTestBean.class);
try {
context.refresh();
fail("Should have thrown a BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getMessage().contains("found 6"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.withMessageContaining("found 6");
}
@Test
@@ -196,13 +192,9 @@ public class QualifierAnnotationTests {
BeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
reader.loadBeanDefinitions(CONFIG_LOCATION);
context.registerSingleton("testBean", QualifiedByAttributesTestBean.class);
try {
context.refresh();
fail("should have thrown a BeanCreationException");
}
catch (BeanCreationException e) {
assertTrue(e.getMessage().contains("found 6"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.withMessageContaining("found 6");
}
@Test

View File

@@ -67,6 +67,8 @@ import org.springframework.util.FileCopyUtils;
import org.springframework.util.SerializationTestUtils;
import org.springframework.util.StopWatch;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
@@ -76,7 +78,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;
/**
* Miscellaneous tests for XML bean definitions.
@@ -428,13 +429,8 @@ public class XmlBeanFactoryTests {
assertTrue(tbs.containsKey("inheritedTestBeanSingleton"));
// abstract bean should throw exception on creation attempt
try {
parent.getBean("inheritedTestBeanWithoutClass");
fail("Should have thrown BeanIsAbstractException");
}
catch (BeanIsAbstractException ex) {
// expected
}
assertThatExceptionOfType(BeanIsAbstractException.class).isThrownBy(() ->
parent.getBean("inheritedTestBeanWithoutClass"));
// non-abstract bean should work, even if it serves as parent
assertTrue(parent.getBean("inheritedTestBeanPrototype") instanceof TestBean);
@@ -484,15 +480,10 @@ public class XmlBeanFactoryTests {
new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT);
DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent);
new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT);
try {
child.getBean("bogusParent", TestBean.class);
fail();
}
catch (BeanDefinitionStoreException ex) {
// check exception message contains the name
assertTrue(ex.getMessage().contains("bogusParent"));
assertTrue(ex.getCause() instanceof NoSuchBeanDefinitionException);
}
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
child.getBean("bogusParent", TestBean.class))
.withMessageContaining("bogusParent")
.withCauseInstanceOf(NoSuchBeanDefinitionException.class);
}
/**
@@ -584,13 +575,9 @@ public class XmlBeanFactoryTests {
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
reader.loadBeanDefinitions(REFTYPES_CONTEXT);
try {
xbf.getBean("jenny");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
xbf.getBean("jenny"))
.matches(ex -> ex.contains(BeanCurrentlyInCreationException.class));
}
@Test
@@ -600,13 +587,9 @@ public class XmlBeanFactoryTests {
reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
reader.loadBeanDefinitions(REFTYPES_CONTEXT);
xbf.addBeanPostProcessor(new WrappingPostProcessor());
try {
xbf.getBean("jenny");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
xbf.getBean("jenny"))
.matches(ex -> ex.contains(BeanCurrentlyInCreationException.class));
}
@Test
@@ -658,11 +641,12 @@ public class XmlBeanFactoryTests {
assertEquals(5, xbf.getSingletonCount());
}
@Test(expected = BeanCreationException.class)
@Test
public void noSuchFactoryBeanMethod() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(NO_SUCH_FACTORY_METHOD_CONTEXT);
assertNotNull(xbf.getBean("defaultTestBean"));
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
xbf.getBean("defaultTestBean"));
}
@Test
@@ -681,31 +665,24 @@ public class XmlBeanFactoryTests {
public void testInitMethodThrowsException() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INITIALIZERS_CONTEXT);
try {
xbf.getBean("init-method2");
fail();
}
catch (BeanCreationException ex) {
assertTrue(ex.getResourceDescription().contains("initializers.xml"));
assertEquals("init-method2", ex.getBeanName());
assertTrue(ex.getCause() instanceof IOException);
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
xbf.getBean("init-method2"))
.withCauseInstanceOf(IOException.class)
.satisfies(ex -> {
assertThat(ex.getResourceDescription()).contains("initializers.xml");
assertThat(ex.getBeanName()).isEqualTo("init-method2");
});
}
@Test
public void testNoSuchInitMethod() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INITIALIZERS_CONTEXT);
try {
xbf.getBean("init-method3");
fail();
}
catch (FatalBeanException ex) {
// check message is helpful
assertTrue(ex.getMessage().contains("initializers.xml"));
assertTrue(ex.getMessage().contains("init-method3"));
assertTrue(ex.getMessage().contains("init"));
}
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() ->
xbf.getBean("init-method3"))
.withMessageContaining("initializers.xml")
.withMessageContaining("init-method3")
.withMessageContaining("init");
}
/**
@@ -766,16 +743,18 @@ public class XmlBeanFactoryTests {
}
}
@Test(expected = BeanDefinitionStoreException.class)
@Test
public void noSuchXmlFile() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(MISSING_CONTEXT);
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(MISSING_CONTEXT));
}
@Test(expected = BeanDefinitionStoreException.class)
@Test
public void invalidXmlFile() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INVALID_CONTEXT);
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INVALID_CONTEXT));
}
@Test
@@ -832,13 +811,8 @@ public class XmlBeanFactoryTests {
assertEquals(kerry, rod3a.getSpouse2());
assertEquals(other, rod3a.getOther());
try {
xbf.getBean("rod4", ConstructorDependenciesBean.class);
fail("Must have thrown a FatalBeanException");
}
catch (FatalBeanException expected) {
// expected
}
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() ->
xbf.getBean("rod4", ConstructorDependenciesBean.class));
DependenciesBean rod5 = (DependenciesBean) xbf.getBean("rod5");
// Should not have been autowired
@@ -1021,18 +995,20 @@ public class XmlBeanFactoryTests {
assertEquals(File.separator + "test", file.getPath());
}
@Test(expected = BeanCreationException.class)
@Test
public void throwsExceptionOnTooManyArguments() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT);
xbf.getBean("rod7", ConstructorDependenciesBean.class);
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
xbf.getBean("rod7", ConstructorDependenciesBean.class));
}
@Test(expected = UnsatisfiedDependencyException.class)
@Test
public void throwsExceptionOnAmbiguousResolution() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT);
xbf.getBean("rod8", ConstructorDependenciesBean.class);
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
xbf.getBean("rod8", ConstructorDependenciesBean.class));
}
@Test
@@ -1117,15 +1093,11 @@ public class XmlBeanFactoryTests {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(factory).loadBeanDefinitions(CLASS_NOT_FOUND_CONTEXT);
// cool, no errors, so the rubbish class name in the bean def was not resolved
try {
// let's resolve the bean definition; must blow up
factory.getBean("classNotFound");
fail("Must have thrown a CannotLoadBeanClassException");
}
catch (CannotLoadBeanClassException ex) {
assertTrue(ex.getResourceDescription().contains("classNotFound.xml"));
assertTrue(ex.getCause() instanceof ClassNotFoundException);
}
// let's resolve the bean definition; must blow up
assertThatExceptionOfType(CannotLoadBeanClassException.class).isThrownBy(() ->
factory.getBean("classNotFound"))
.withCauseInstanceOf(ClassNotFoundException.class)
.satisfies(ex -> assertThat(ex.getResourceDescription()).contains("classNotFound.xml"));
}
@Test
@@ -1193,10 +1165,11 @@ public class XmlBeanFactoryTests {
xbf.getBean("resource2", ResourceTestBean.class);
}
@Test(expected = BeanDefinitionStoreException.class)
@Test
public void recursiveImport() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(RECURSIVE_IMPORT_CONTEXT);
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(RECURSIVE_IMPORT_CONTEXT));
}
/**
@@ -1368,15 +1341,10 @@ public class XmlBeanFactoryTests {
public void testRejectsOverrideOfBogusMethodName() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
try {
reader.loadBeanDefinitions(INVALID_NO_SUCH_METHOD_CONTEXT);
xbf.getBean("constructorOverrides");
fail("Shouldn't allow override of bogus method");
}
catch (BeanDefinitionStoreException ex) {
// Check that the bogus method name was included in the error message
assertTrue("Bogus method name correctly reported", ex.getMessage().contains("bogusMethod"));
}
reader.loadBeanDefinitions(INVALID_NO_SUCH_METHOD_CONTEXT);
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
xbf.getBean("constructorOverrides"))
.withMessageContaining("bogusMethod");
}
@Test
@@ -1480,15 +1448,9 @@ public class XmlBeanFactoryTests {
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT);
AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("lenientDependencyTestBean");
bd.setLenientConstructorResolution(false);
try {
xbf.getBean("lenientDependencyTestBean");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
// expected
ex.printStackTrace();
assertTrue(ex.getMostSpecificCause().getMessage().contains("Ambiguous"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
xbf.getBean("lenientDependencyTestBean"))
.satisfies(ex -> assertThat(ex.getMostSpecificCause().getMessage()).contains("Ambiguous"));
}
@Test
@@ -1497,15 +1459,9 @@ public class XmlBeanFactoryTests {
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT);
AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("lenientDependencyTestBeanFactoryMethod");
bd.setLenientConstructorResolution(false);
try {
xbf.getBean("lenientDependencyTestBeanFactoryMethod");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
// expected
ex.printStackTrace();
assertTrue(ex.getMostSpecificCause().getMessage().contains("Ambiguous"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
xbf.getBean("lenientDependencyTestBeanFactoryMethod"))
.satisfies(ex -> assertThat(ex.getMostSpecificCause().getMessage()).contains("Ambiguous"));
}
@Test
@@ -1581,25 +1537,17 @@ public class XmlBeanFactoryTests {
@Test
public void testWithDuplicateName() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
try {
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(TEST_WITH_DUP_NAMES_CONTEXT);
fail("Duplicate name not detected");
}
catch (BeansException ex) {
assertTrue(ex.getMessage().contains("Bean name 'foo'"));
}
assertThatExceptionOfType(BeansException.class).isThrownBy(() ->
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(TEST_WITH_DUP_NAMES_CONTEXT))
.withMessageContaining("Bean name 'foo'");
}
@Test
public void testWithDuplicateNameInAlias() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
try {
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(TEST_WITH_DUP_NAME_IN_ALIAS_CONTEXT);
fail("Duplicate name not detected");
}
catch (BeansException e) {
assertTrue(e.getMessage().contains("Bean name 'foo'"));
}
assertThatExceptionOfType(BeansException.class).isThrownBy(() ->
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(TEST_WITH_DUP_NAME_IN_ALIAS_CONTEXT))
.withMessageContaining("Bean name 'foo'");
}
@Test
@@ -1676,9 +1624,7 @@ public class XmlBeanFactoryTests {
@Override
public void afterPropertiesSet() {
if (this.initMethodInvoked) {
fail();
}
assertThat(this.initMethodInvoked).isFalse();
if (this.afterPropertiesSetInvoked) {
throw new IllegalStateException("Already initialized");
}
@@ -1687,9 +1633,7 @@ public class XmlBeanFactoryTests {
/** Init method */
public void customInit() throws IOException {
if (!this.afterPropertiesSetInvoked) {
fail();
}
assertThat(this.afterPropertiesSetInvoked).isTrue();
if (this.initMethodInvoked) {
throw new IllegalStateException("Already customInitialized");
}
@@ -1698,9 +1642,7 @@ public class XmlBeanFactoryTests {
@Override
public void destroy() {
if (this.customDestroyed) {
fail();
}
assertThat(this.customDestroyed).isFalse();
if (this.destroyed) {
throw new IllegalStateException("Already destroyed");
}
@@ -1708,9 +1650,7 @@ public class XmlBeanFactoryTests {
}
public void customDestroy() {
if (!this.destroyed) {
fail();
}
assertThat(this.destroyed).isTrue();
if (this.customDestroyed) {
throw new IllegalStateException("Already customDestroyed");
}

View File

@@ -60,10 +60,11 @@ import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean;
import static java.lang.String.format;
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.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for custom XML namespace handler implementations.
@@ -126,13 +127,9 @@ public class CustomNamespaceHandlerTests {
String[] beanNames = this.beanFactory.getBeanNamesForType(ApplicationListener.class);
assertTrue(Arrays.asList(beanNames).contains("debuggingTestBeanNoInstance"));
assertEquals(ApplicationListener.class, this.beanFactory.getType("debuggingTestBeanNoInstance"));
try {
this.beanFactory.getBean("debuggingTestBeanNoInstance");
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.getRootCause() instanceof BeanInstantiationException);
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
this.beanFactory.getBean("debuggingTestBeanNoInstance"))
.satisfies(ex -> assertThat(ex.getRootCause()).isInstanceOf(BeanInstantiationException.class));
}
@Test

View File

@@ -46,7 +46,6 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -225,7 +224,7 @@ public class CacheReproTests {
@Cacheable("smallCache")
public List<String> single(int id) {
if (this.multipleCount > 0) {
fail("Called too many times");
throw new AssertionError("Called too many times");
}
this.multipleCount++;
return Collections.emptyList();
@@ -237,7 +236,7 @@ public class CacheReproTests {
@Cacheable(cacheNames = "smallCache", unless = "#result.size() > 3")})
public List<String> multiple(int id) {
if (this.multipleCount > 0) {
fail("Called too many times");
throw new AssertionError("Called too many times");
}
this.multipleCount++;
return Collections.emptyList();

View File

@@ -16,7 +16,6 @@
package org.springframework.cache.config;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;
@@ -30,6 +29,8 @@ import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.ConfigurableApplicationContext;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
@@ -39,7 +40,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;
/**
* Abstract cache annotation tests (containing several reusable methods).
@@ -336,49 +336,28 @@ public abstract class AbstractCacheAnnotationTests {
public void testCheckedThrowable(CacheableService<?> service) throws Exception {
String arg = UUID.randomUUID().toString();
try {
service.throwChecked(arg);
fail("Excepted exception");
}
catch (Exception ex) {
assertEquals("Wrong exception type", IOException.class, ex.getClass());
assertEquals(arg, ex.getMessage());
}
assertThatIOException().isThrownBy(() ->
service.throwChecked(arg))
.withMessage(arg);
}
public void testUncheckedThrowable(CacheableService<?> service) throws Exception {
try {
service.throwUnchecked(1L);
fail("Excepted exception");
}
catch (RuntimeException ex) {
assertEquals("Wrong exception type", UnsupportedOperationException.class, ex.getClass());
assertEquals("1", ex.getMessage());
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
service.throwUnchecked(1L))
.withMessage("1");
}
public void testCheckedThrowableSync(CacheableService<?> service) throws Exception {
String arg = UUID.randomUUID().toString();
try {
service.throwCheckedSync(arg);
fail("Excepted exception");
}
catch (Exception ex) {
ex.printStackTrace();
assertEquals("Wrong exception type", IOException.class, ex.getClass());
assertEquals(arg, ex.getMessage());
}
assertThatIOException().isThrownBy(() ->
service.throwCheckedSync(arg))
.withMessage(arg);
}
public void testUncheckedThrowableSync(CacheableService<?> service) throws Exception {
try {
service.throwUncheckedSync(1L);
fail("Excepted exception");
}
catch (RuntimeException ex) {
assertEquals("Wrong exception type", UnsupportedOperationException.class, ex.getClass());
assertEquals("1", ex.getMessage());
}
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
service.throwUncheckedSync(1L))
.withMessage("1");
}
public void testNullArg(CacheableService<?> service) {
@@ -709,14 +688,9 @@ public abstract class AbstractCacheAnnotationTests {
@Test
public void testUnknownCustomKeyGenerator() {
try {
Object param = new Object();
this.cs.unknownCustomKeyGenerator(param);
fail("should have failed with NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
Object param = new Object();
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
this.cs.unknownCustomKeyGenerator(param));
}
@Test
@@ -732,14 +706,9 @@ public abstract class AbstractCacheAnnotationTests {
@Test
public void testUnknownCustomCacheManager() {
try {
Object param = new Object();
this.cs.unknownCustomCacheManager(param);
fail("should have failed with NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
Object param = new Object();
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
this.cs.unknownCustomCacheManager(param));
}
@Test

View File

@@ -21,7 +21,7 @@ import org.junit.Test;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.context.support.GenericXmlApplicationContext;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* AOP advice specific parsing tests.
@@ -32,13 +32,9 @@ public class CacheAdviceParserTests {
@Test
public void keyAndKeyGeneratorCannotBeSetTogether() {
try {
new GenericXmlApplicationContext("/org/springframework/cache/config/cache-advice-invalid.xml");
fail("Should have failed to load context, one advise define both a key and a key generator");
}
catch (BeanDefinitionStoreException ex) {
// TODO better exception handling
}
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
new GenericXmlApplicationContext("/org/springframework/cache/config/cache-advice-invalid.xml"));
// TODO better exception handling
}
}

View File

@@ -34,9 +34,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
@@ -74,17 +73,9 @@ public class CustomInterceptorTests {
@Test
public void customInterceptorAppliesWithCheckedException() {
try {
this.cs.throwChecked(0L);
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(() ->
this.cs.throwChecked(0L))
.withCauseExactlyInstanceOf(IOException.class);
}

View File

@@ -39,9 +39,9 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.util.ReflectionUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.springframework.cache.CacheTestUtils.assertCacheHit;
import static org.springframework.cache.CacheTestUtils.assertCacheMiss;
@@ -134,24 +134,16 @@ public class CacheResolverCustomizationTests {
@Test
public void noCacheResolved() {
Method method = ReflectionUtils.findMethod(SimpleService.class, "noCacheResolved", Object.class);
try {
this.simpleService.noCacheResolved(new Object());
fail("Should have failed, no cache resolved");
}
catch (IllegalStateException ex) {
assertTrue("Reference to the method must be contained in the message", ex.getMessage().contains(method.toString()));
}
assertThatIllegalStateException().isThrownBy(() ->
this.simpleService.noCacheResolved(new Object()))
.withMessageContaining(method.toString());
}
@Test
public void unknownCacheResolver() {
try {
this.simpleService.unknownCacheResolver(new Object());
fail("Should have failed, no cache resolver with that name");
}
catch (NoSuchBeanDefinitionException ex) {
assertEquals("Wrong bean name in exception", "unknownCacheResolver", ex.getBeanName());
}
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
this.simpleService.unknownCacheResolver(new Object()))
.satisfies(ex -> assertThat(ex.getBeanName()).isEqualTo("unknownCacheResolver"));
}

View File

@@ -36,13 +36,14 @@ import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Costin Leau
@@ -124,13 +125,9 @@ public class ExpressionEvaluatorTests {
@Test
public void unavailableReturnValue() {
EvaluationContext context = createEvaluationContext(CacheOperationExpressionEvaluator.RESULT_UNAVAILABLE);
try {
new SpelExpressionParser().parseExpression("#result").getValue(context);
fail("Should have failed to parse expression, result not available");
}
catch (VariableNotAvailableException e) {
assertEquals("wrong variable name", "result", e.getName());
}
assertThatExceptionOfType(VariableNotAvailableException.class).isThrownBy(() ->
new SpelExpressionParser().parseExpression("#result").getValue(context))
.satisfies(ex -> assertThat(ex.getName()).isEqualTo("result"));
}
@Test

View File

@@ -30,6 +30,7 @@ import org.springframework.beans.factory.xml.AbstractListableBeanFactoryTests;
import org.springframework.tests.sample.beans.LifecycleBean;
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;
@@ -134,12 +135,12 @@ public abstract class AbstractApplicationContextTests extends AbstractListableBe
assertTrue("Destroyed", lb.isDestroyed());
}
@Test(expected = NoSuchMessageException.class)
@Test
public void messageSource() throws NoSuchMessageException {
assertEquals("message1", applicationContext.getMessage("code1", null, Locale.getDefault()));
assertEquals("message2", applicationContext.getMessage("code2", null, Locale.getDefault()));
applicationContext.getMessage("code0", null, Locale.getDefault());
assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() ->
applicationContext.getMessage("code0", null, Locale.getDefault()));
}
@Test

View File

@@ -34,6 +34,7 @@ import org.springframework.core.ResolvableType;
import org.springframework.util.ObjectUtils;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
@@ -45,7 +46,6 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.util.StringUtils.uncapitalize;
/**
@@ -106,13 +106,9 @@ public class AnnotationConfigApplicationContextTests {
// attempt to retrieve a bean that does not exist
Class<?> targetType = Pattern.class;
try {
context.getBean(targetType);
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
assertThat(ex.getMessage(), containsString(format("No qualifying bean of type '%s'", targetType.getName())));
}
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
context.getBean(targetType))
.withMessageContaining(format("No qualifying bean of type '%s'", targetType.getName()));
}
@Test

View File

@@ -29,6 +29,7 @@ import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.context.annotation.ScopedProxyMode.INTERFACES;
@@ -117,14 +118,16 @@ public class AnnotationScopeMetadataResolverTests {
assertEquals(TARGET_CLASS, scopeMetadata.getScopedProxyMode());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void ctorWithNullScopedProxyMode() {
new AnnotationScopeMetadataResolver(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new AnnotationScopeMetadataResolver(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void setScopeAnnotationTypeWithNullType() {
scopeMetadataResolver.setScopeAnnotationType(null);
assertThatIllegalArgumentException().isThrownBy(() ->
scopeMetadataResolver.setScopeAnnotationType(null));
}

View File

@@ -39,11 +39,13 @@ import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.stereotype.Component;
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.assertThatIllegalStateException;
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 Mark Fisher
@@ -149,16 +151,11 @@ public class ClassPathBeanDefinitionScannerTests {
GenericApplicationContext context = new GenericApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
scanner.setIncludeAnnotationConfig(false);
try {
scanner.scan("org.springframework.context.annotation3");
scanner.scan(BASE_PACKAGE);
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
assertTrue(ex.getMessage().contains("stubFooDao"));
assertTrue(ex.getMessage().contains(StubFooDao.class.getName()));
}
scanner.scan("org.springframework.context.annotation3");
assertThatIllegalStateException().isThrownBy(() ->
scanner.scan(BASE_PACKAGE))
.withMessageContaining("stubFooDao")
.withMessageContaining(StubFooDao.class.getName());
}
@Test
@@ -214,16 +211,12 @@ public class ClassPathBeanDefinitionScannerTests {
GenericApplicationContext context = new GenericApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
scanner.setIncludeAnnotationConfig(false);
try {
scanner.scan("org.springframework.context.annotation2");
scanner.scan(BASE_PACKAGE);
fail("Must have thrown IllegalStateException");
}
catch (IllegalStateException expected) {
assertTrue(expected.getMessage().contains("myNamedDao"));
assertTrue(expected.getMessage().contains(NamedStubDao.class.getName()));
assertTrue(expected.getMessage().contains(NamedStubDao2.class.getName()));
}
scanner.scan("org.springframework.context.annotation2");
assertThatIllegalStateException().isThrownBy(() ->
scanner.scan(BASE_PACKAGE))
.withMessageContaining("myNamedDao")
.withMessageContaining(NamedStubDao.class.getName())
.withMessageContaining(NamedStubDao2.class.getName());
}
@Test
@@ -472,15 +465,10 @@ public class ClassPathBeanDefinitionScannerTests {
scanner.setBeanNameGenerator(new TestBeanNameGenerator());
scanner.setAutowireCandidatePatterns("*NoSuchDao");
scanner.scan(BASE_PACKAGE);
try {
context.refresh();
context.getBean("fooService");
fail("BeanCreationException expected; fooDao should not have been an autowire-candidate");
}
catch (BeanCreationException expected) {
assertTrue(expected.getMostSpecificCause() instanceof NoSuchBeanDefinitionException);
}
context.refresh();
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
context.getBean("fooService"))
.satisfies(ex -> assertThat(ex.getMostSpecificCause()).isInstanceOf(NoSuchBeanDefinitionException.class));
}

View File

@@ -23,12 +23,12 @@ import org.springframework.beans.factory.UnsatisfiedDependencyException;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.GenericApplicationContext;
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;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Mark Fisher
@@ -123,13 +123,8 @@ public class ComponentScanParserBeanDefinitionDefaultsTests {
GenericApplicationContext context = new GenericApplicationContext();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultAutowireByTypeTests.xml");
try {
context.refresh();
fail("expected exception due to multiple matches for byType autowiring");
}
catch (UnsatisfiedDependencyException ex) {
// expected
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
context::refresh);
}
@Test

View File

@@ -23,10 +23,10 @@ import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Mark Fisher
@@ -51,26 +51,16 @@ public class ComponentScanParserWithUserDefinedStrategiesTests {
@Test
public void testInvalidConstructorBeanNameGenerator() {
try {
assertThatExceptionOfType(BeansException.class).isThrownBy(() ->
new ClassPathXmlApplicationContext(
"org/springframework/context/annotation/invalidConstructorNameGeneratorTests.xml");
fail("should have failed: no-arg constructor is required");
}
catch (BeansException ex) {
// expected
}
"org/springframework/context/annotation/invalidConstructorNameGeneratorTests.xml"));
}
@Test
public void testInvalidClassNameScopeMetadataResolver() {
try {
new ClassPathXmlApplicationContext(
"org/springframework/context/annotation/invalidClassNameScopeResolverTests.xml");
fail("should have failed: no such class");
}
catch (BeansException ex) {
// expected
}
assertThatExceptionOfType(BeansException.class).isThrownBy(() ->
new ClassPathXmlApplicationContext(
"org/springframework/context/annotation/invalidClassNameScopeResolverTests.xml"));
}
}

View File

@@ -64,12 +64,13 @@ import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Chris Beams
@@ -318,13 +319,8 @@ public class ConfigurationClassPostProcessorTests {
ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor();
pp.setEnvironment(new StandardEnvironment());
pp.postProcessBeanFactory(beanFactory);
try {
beanFactory.getBean(SimpleComponent.class);
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
beanFactory.getBean(SimpleComponent.class));
}
@Test
@@ -374,15 +370,11 @@ public class ConfigurationClassPostProcessorTests {
beanFactory.registerBeanDefinition("config", new RootBeanDefinition(SingletonBeanConfig.class));
beanFactory.setAllowBeanDefinitionOverriding(false);
ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor();
try {
pp.postProcessBeanFactory(beanFactory);
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
assertTrue(ex.getMessage().contains("bar"));
assertTrue(ex.getMessage().contains("SingletonBeanConfig"));
assertTrue(ex.getMessage().contains(TestBean.class.getName()));
}
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
pp.postProcessBeanFactory(beanFactory))
.withMessageContaining("bar")
.withMessageContaining("SingletonBeanConfig")
.withMessageContaining(TestBean.class.getName());
}
@Test
@@ -420,16 +412,12 @@ public class ConfigurationClassPostProcessorTests {
ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor();
pp.postProcessBeanFactory(beanFactory);
try {
beanFactory.getBean(Bar.class);
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.getMessage().contains("OverridingSingletonBeanConfig.foo"));
assertTrue(ex.getMessage().contains(ExtendedFoo.class.getName()));
assertTrue(ex.getMessage().contains(Foo.class.getName()));
assertTrue(ex.getMessage().contains("InvalidOverridingSingletonBeanConfig"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
beanFactory.getBean(Bar.class))
.withMessageContaining("OverridingSingletonBeanConfig.foo")
.withMessageContaining(ExtendedFoo.class.getName())
.withMessageContaining(Foo.class.getName())
.withMessageContaining("InvalidOverridingSingletonBeanConfig");
}
@Test // SPR-15384
@@ -479,19 +467,11 @@ public class ConfigurationClassPostProcessorTests {
DefaultListableBeanFactory bf2 = new DefaultListableBeanFactory();
ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor();
pp.postProcessBeanFactory(bf1); // first invocation -- should succeed
try {
pp.postProcessBeanFactory(bf1); // second invocation for bf1 -- should throw
fail("expected exception");
}
catch (IllegalStateException ex) {
}
assertThatIllegalStateException().isThrownBy(() ->
pp.postProcessBeanFactory(bf1)); // second invocation for bf1 -- should throw
pp.postProcessBeanFactory(bf2); // first invocation for bf2 -- should succeed
try {
pp.postProcessBeanFactory(bf2); // second invocation for bf2 -- should throw
fail("expected exception");
}
catch (IllegalStateException ex) {
}
assertThatIllegalStateException().isThrownBy(() ->
pp.postProcessBeanFactory(bf2)); // second invocation for bf2 -- should throw
}
@Test
@@ -985,24 +965,16 @@ public class ConfigurationClassPostProcessorTests {
beanFactory.registerBeanDefinition("configClass1", new RootBeanDefinition(A.class));
beanFactory.registerBeanDefinition("configClass2", new RootBeanDefinition(AStrich.class));
new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory);
try {
beanFactory.preInstantiateSingletons();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.getMessage().contains("Circular reference"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
beanFactory::preInstantiateSingletons)
.withMessageContaining("Circular reference");
}
@Test
public void testCircularDependencyWithApplicationContext() {
try {
new AnnotationConfigApplicationContext(A.class, AStrich.class);
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.getMessage().contains("Circular reference"));
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
new AnnotationConfigApplicationContext(A.class, AStrich.class))
.withMessageContaining("Circular reference");
}
@Test
@@ -1106,10 +1078,12 @@ public class ConfigurationClassPostProcessorTests {
assertSame(ctx.getBean(TestBean.class), bean.getTestBean());
}
@Test(expected = BeanDefinitionStoreException.class)
@Test
public void testNameClashBetweenConfigurationClassAndBean() {
ApplicationContext ctx = new AnnotationConfigApplicationContext(MyTestBean.class);
ctx.getBean("myTestBean", TestBean.class);
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> {
ApplicationContext ctx = new AnnotationConfigApplicationContext(MyTestBean.class);
ctx.getBean("myTestBean", TestBean.class);
});
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 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.
@@ -21,36 +21,41 @@ import org.junit.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.support.RootBeanDefinition;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Andy Wilkinson
*/
public class ImportVersusDirectRegistrationTests {
@Test(expected = NoSuchBeanDefinitionException.class)
@Test
public void thingIsNotAvailableWhenOuterConfigurationIsRegisteredDirectly() {
try (AnnotationConfigApplicationContext directRegistration = new AnnotationConfigApplicationContext()) {
directRegistration.register(AccidentalLiteConfiguration.class);
directRegistration.refresh();
directRegistration.getBean(Thing.class);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
directRegistration.getBean(Thing.class));
}
}
@Test(expected = NoSuchBeanDefinitionException.class)
@Test
public void thingIsNotAvailableWhenOuterConfigurationIsRegisteredWithClassName() {
try (AnnotationConfigApplicationContext directRegistration = new AnnotationConfigApplicationContext()) {
directRegistration.registerBeanDefinition("config",
new RootBeanDefinition(AccidentalLiteConfiguration.class.getName()));
directRegistration.refresh();
directRegistration.getBean(Thing.class);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
directRegistration.getBean(Thing.class));
}
}
@Test(expected = NoSuchBeanDefinitionException.class)
@Test
public void thingIsNotAvailableWhenOuterConfigurationIsImported() {
try (AnnotationConfigApplicationContext viaImport = new AnnotationConfigApplicationContext()) {
viaImport.register(Importer.class);
viaImport.refresh();
viaImport.getBean(Thing.class);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
viaImport.getBean(Thing.class));
}
}

View File

@@ -21,8 +21,7 @@ import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
/**
@@ -43,14 +42,10 @@ public class InvalidConfigurationClassDefinitionTests {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.registerBeanDefinition("config", configBeanDef);
try {
ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor();
pp.postProcessBeanFactory(beanFactory);
fail("expected exception");
}
catch (BeanDefinitionParsingException ex) {
assertTrue(ex.getMessage(), ex.getMessage().contains("Remove the final modifier"));
}
ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor();
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() ->
pp.postProcessBeanFactory(beanFactory))
.withMessageContaining("Remove the final modifier");
}
}

View File

@@ -29,12 +29,12 @@ 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.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@@ -133,13 +133,8 @@ public class LazyAutowiredAnnotationBeanPostProcessorTests {
FieldResourceInjectionBean bean = (FieldResourceInjectionBean) bf.getBean("annotatedBean");
assertNotNull(bean.getTestBean());
try {
bean.getTestBean().getName();
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
bean.getTestBean().getName());
}
@Test
@@ -157,13 +152,8 @@ public class LazyAutowiredAnnotationBeanPostProcessorTests {
assertNotNull(bean.getTestBean());
assertNotNull(bean.getTestBeans());
assertTrue(bean.getTestBeans().isEmpty());
try {
bean.getTestBean().getName();
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
bean.getTestBean().getName());
}

View File

@@ -65,12 +65,12 @@ import org.springframework.validation.annotation.Validated;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Stephane Nicoll
@@ -299,13 +299,9 @@ public class AnnotationDrivenEventListenerTests {
@Test
public void privateMethodOnCglibProxyFails() throws Exception {
try {
load(CglibProxyWithPrivateMethod.class);
fail("Should have thrown BeanInitializationException");
}
catch (BeanInitializationException ex) {
assertTrue(ex.getCause() instanceof IllegalStateException);
}
assertThatExceptionOfType(BeanInitializationException.class).isThrownBy(() ->
load(CglibProxyWithPrivateMethod.class))
.withCauseInstanceOf(IllegalStateException.class);
}
@Test
@@ -331,15 +327,10 @@ public class AnnotationDrivenEventListenerTests {
this.eventCollector.assertEvent(proxy.getId(), event);
this.eventCollector.assertTotalEventsCount(1);
try {
customScope.active = false;
this.context.publishEvent(new TestEvent());
fail("Should have thrown IllegalStateException");
}
catch (BeanCreationException ex) {
// expected
assertTrue(ex.getCause() instanceof IllegalStateException);
}
customScope.active = false;
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
this.context.publishEvent(new TestEvent()))
.withCauseInstanceOf(IllegalStateException.class);
}
@Test
@@ -393,15 +384,11 @@ public class AnnotationDrivenEventListenerTests {
TestEvent event = new TestEvent(this, "fail");
ExceptionEventListener listener = this.context.getBean(ExceptionEventListener.class);
this.eventCollector.assertNoEventReceived(listener);
try {
this.context.publishEvent(event);
fail("An exception should have thrown");
}
catch (IllegalStateException e) {
assertEquals("Wrong exception", "Test exception", e.getMessage());
this.eventCollector.assertEvent(listener, event);
this.eventCollector.assertTotalEventsCount(1);
}
assertThatIllegalStateException().isThrownBy(() ->
this.context.publishEvent(event))
.withMessage("Test exception");
this.eventCollector.assertEvent(listener, event);
this.eventCollector.assertTotalEventsCount(1);
}
@Test

View File

@@ -48,11 +48,12 @@ import org.springframework.scheduling.support.TaskUtils;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
@@ -164,13 +165,9 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen
RuntimeException thrown = new RuntimeException();
willThrow(thrown).given(listener).onApplicationEvent(evt);
try {
smc.multicastEvent(evt);
fail("Should have thrown RuntimeException");
}
catch (RuntimeException ex) {
assertSame(thrown, ex);
}
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
smc.multicastEvent(evt))
.satisfies(ex -> assertThat(ex).isSameAs(thrown));
}
@Test

View File

@@ -31,6 +31,7 @@ import org.springframework.context.support.StaticApplicationContext;
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.assertTrue;
import static org.mockito.Mockito.mock;
@@ -49,35 +50,42 @@ public class EventPublicationInterceptorTests {
this.publisher = mock(ApplicationEventPublisher.class);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithNoApplicationEventClassSupplied() throws Exception {
EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
interceptor.setApplicationEventPublisher(this.publisher);
interceptor.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(
interceptor::afterPropertiesSet);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithNonApplicationEventClassSupplied() throws Exception {
EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
interceptor.setApplicationEventPublisher(this.publisher);
interceptor.setApplicationEventClass(getClass());
interceptor.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> {
interceptor.setApplicationEventClass(getClass());
interceptor.afterPropertiesSet();
});
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithAbstractStraightApplicationEventClassSupplied() throws Exception {
EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
interceptor.setApplicationEventPublisher(this.publisher);
interceptor.setApplicationEventClass(ApplicationEvent.class);
interceptor.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> {
interceptor.setApplicationEventClass(ApplicationEvent.class);
interceptor.afterPropertiesSet();
});
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithApplicationEventClassThatDoesntExposeAValidCtor() throws Exception {
EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
interceptor.setApplicationEventPublisher(this.publisher);
interceptor.setApplicationEventClass(TestEventWithNoValidOneArgObjectCtor.class);
interceptor.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(() -> {
interceptor.setApplicationEventClass(TestEventWithNoValidOneArgObjectCtor.class);
interceptor.afterPropertiesSet();
});
}
@Test

View File

@@ -21,7 +21,6 @@ import org.junit.Test;
import org.springframework.beans.factory.BeanIsNotAFactoryException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.expression.FactoryBeanAccessTests.SimpleBeanResolver.Boat;
import org.springframework.context.expression.FactoryBeanAccessTests.SimpleBeanResolver.CarFactoryBean;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.expression.AccessException;
@@ -30,8 +29,8 @@ import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* Unit tests for expressions accessing beans and factory beans.
@@ -51,34 +50,19 @@ public class FactoryBeanAccessTests {
expr = new SpelExpressionParser().parseRaw("@boat.colour");
assertEquals("blue",expr.getValue(context));
expr = new SpelExpressionParser().parseRaw("&boat.class.name");
try {
assertEquals(Boat.class.getName(), expr.getValue(context));
fail("Expected BeanIsNotAFactoryException");
}
catch (BeanIsNotAFactoryException binafe) {
// success
}
Expression notFactoryExpr = new SpelExpressionParser().parseRaw("&boat.class.name");
assertThatExceptionOfType(BeanIsNotAFactoryException.class).isThrownBy(() ->
notFactoryExpr.getValue(context));
// No such bean
try {
expr = new SpelExpressionParser().parseRaw("@truck");
assertEquals("red", expr.getValue(context));
fail("Expected NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException nsbde) {
// success
}
Expression noBeanExpr = new SpelExpressionParser().parseRaw("@truck");
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
noBeanExpr.getValue(context));
// No such factory bean
try {
expr = new SpelExpressionParser().parseRaw("&truck");
assertEquals(CarFactoryBean.class.getName(), expr.getValue(context));
fail("Expected NoSuchBeanDefinitionException");
}
catch (NoSuchBeanDefinitionException nsbde) {
// success
}
Expression noFactoryBeanExpr = new SpelExpressionParser().parseRaw("&truck");
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
noFactoryBeanExpr.getValue(context));
}
static class SimpleBeanResolver

View File

@@ -21,6 +21,7 @@ import org.junit.Test;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
import org.springframework.context.support.GenericGroovyApplicationContext;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@@ -70,9 +71,10 @@ public class GroovyApplicationContextTests {
assertEquals("SpringSource", company);
}
@Test(expected = BeanDefinitionParsingException.class)
@Test
public void testConfigFileParsingError() {
new GenericGroovyApplicationContext("org/springframework/context/groovy/applicationContext-error.groovy");
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() ->
new GenericGroovyApplicationContext("org/springframework/context/groovy/applicationContext-error.groovy"));
}
}

View File

@@ -43,12 +43,13 @@ import org.springframework.tests.sample.beans.ResourceTestBean;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ObjectUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@@ -141,39 +142,37 @@ public class ClassPathXmlApplicationContextTests {
public void testContextWithInvalidValueType() throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {INVALID_VALUE_TYPE_CONTEXT}, false);
try {
context.refresh();
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
assertTrue(ex.contains(TypeMismatchException.class));
assertTrue(ex.toString().contains("someMessageSource"));
assertTrue(ex.toString().contains("useCodeAsDefaultMessage"));
checkExceptionFromInvalidValueType(ex);
checkExceptionFromInvalidValueType(new ExceptionInInitializerError(ex));
assertFalse(context.isActive());
}
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh)
.satisfies(ex -> {
assertThat(ex.contains(TypeMismatchException.class)).isTrue();
assertThat(ex.toString()).contains("someMessageSource", "useCodeAsDefaultMessage");
checkExceptionFromInvalidValueType(ex);
checkExceptionFromInvalidValueType(new ExceptionInInitializerError(ex));
assertFalse(context.isActive());
});
}
private void checkExceptionFromInvalidValueType(Throwable ex) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ex.printStackTrace(new PrintStream(baos));
String dump = FileCopyUtils.copyToString(new InputStreamReader(new ByteArrayInputStream(baos.toByteArray())));
assertTrue(dump.contains("someMessageSource"));
assertTrue(dump.contains("useCodeAsDefaultMessage"));
private void checkExceptionFromInvalidValueType(Throwable ex) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ex.printStackTrace(new PrintStream(baos));
String dump = FileCopyUtils.copyToString(new InputStreamReader(new ByteArrayInputStream(baos.toByteArray())));
assertTrue(dump.contains("someMessageSource"));
assertTrue(dump.contains("useCodeAsDefaultMessage"));
}
catch (IOException ioex) {
throw new IllegalStateException(ioex);
}
}
@Test
public void testContextWithInvalidLazyClass() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(INVALID_CLASS_CONTEXT, getClass());
assertTrue(ctx.containsBean("someMessageSource"));
try {
ctx.getBean("someMessageSource");
fail("Should have thrown CannotLoadBeanClassException");
}
catch (CannotLoadBeanClassException ex) {
assertTrue(ex.contains(ClassNotFoundException.class));
}
assertThatExceptionOfType(CannotLoadBeanClassException.class).isThrownBy(() ->
ctx.getBean("someMessageSource"))
.satisfies(ex -> assertThat(ex.contains(ClassNotFoundException.class)).isTrue());
ctx.close();
}

View File

@@ -34,6 +34,7 @@ import org.springframework.core.io.FileSystemResource;
import org.springframework.lang.Nullable;
import org.springframework.tests.sample.beans.ResourceTestBean;
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.assertTrue;
@@ -94,13 +95,14 @@ public class ConversionServiceFactoryBeanTests {
assertTrue(service.canConvert(String.class, Baz.class));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void createDefaultConversionServiceWithInvalidSupplements() {
ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
Set<Object> converters = new HashSet<>();
converters.add("bogus");
factory.setConverters(converters);
factory.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(
factory::afterPropertiesSet);
}
@Test

View File

@@ -24,13 +24,14 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.ObjectUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@@ -48,13 +49,8 @@ public class GenericApplicationContextTests {
assertSame(ac.getBean("testBean"), ac.getBean(String.class));
assertSame(ac.getBean("testBean"), ac.getBean(CharSequence.class));
try {
assertSame(ac.getBean("testBean"), ac.getBean(Object.class));
fail("Should have thrown NoUniqueBeanDefinitionException");
}
catch (NoUniqueBeanDefinitionException ex) {
// expected
}
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() ->
ac.getBean(Object.class));
}
@Test
@@ -94,22 +90,13 @@ public class GenericApplicationContextTests {
ac.close();
try {
assertSame(ac.getBean("testBean"), ac.getBean(String.class));
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
ac.getBean(String.class));
try {
assertSame(ac.getAutowireCapableBeanFactory().getBean("testBean"),
ac.getAutowireCapableBeanFactory().getBean(String.class));
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() -> {
ac.getAutowireCapableBeanFactory().getBean("testBean");
ac.getAutowireCapableBeanFactory().getBean(String.class);
});
}
@Test

View File

@@ -31,8 +31,7 @@ import org.springframework.context.ApplicationContext;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.StringUtils;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Integration tests for {@link PropertyResourceConfigurer} implementations requiring
@@ -54,20 +53,11 @@ public class PropertyResourceConfigurerIntegrationTests {
pvs = new MutablePropertyValues();
pvs.add("location", "${user.dir}/test");
ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanInitializationException");
}
catch (BeanInitializationException ex) {
// expected
assertTrue(ex.getCause() instanceof FileNotFoundException);
// slight hack for Linux/Unix systems
String userDir = StringUtils.cleanPath(System.getProperty("user.dir"));
if (userDir.startsWith("/")) {
userDir = userDir.substring(1);
}
assertTrue(ex.getMessage().contains(userDir));
}
String userDir = getUserDir();
assertThatExceptionOfType(BeanInitializationException.class).isThrownBy(
ac::refresh)
.withCauseInstanceOf(FileNotFoundException.class)
.withMessageContaining(userDir);
}
@Test
@@ -79,24 +69,21 @@ public class PropertyResourceConfigurerIntegrationTests {
pvs = new MutablePropertyValues();
pvs.add("location", "${user.dir}/test/${user.dir}");
ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanInitializationException");
}
catch (BeanInitializationException ex) {
// expected
assertTrue(ex.getCause() instanceof FileNotFoundException);
// slight hack for Linux/Unix systems
String userDir = StringUtils.cleanPath(System.getProperty("user.dir"));
if (userDir.startsWith("/")) {
userDir = userDir.substring(1);
}
/* the above hack doesn't work since the exception message is created without
the leading / stripped so the test fails. Changed 17/11/04. DD */
//assertTrue(ex.getMessage().indexOf(userDir + "/test/" + userDir) != -1);
assertTrue(ex.getMessage().contains(userDir + "/test/" + userDir) ||
String userDir = getUserDir();
assertThatExceptionOfType(BeanInitializationException.class).isThrownBy(
ac::refresh)
.withCauseInstanceOf(FileNotFoundException.class)
.matches(ex -> ex.getMessage().contains(userDir + "/test/" + userDir) ||
ex.getMessage().contains(userDir + "/test//" + userDir));
}
private String getUserDir() {
// slight hack for Linux/Unix systems
String userDir = StringUtils.cleanPath(System.getProperty("user.dir"));
if (userDir.startsWith("/")) {
userDir = userDir.substring(1);
}
return userDir;
}
@Test
@@ -108,14 +95,9 @@ public class PropertyResourceConfigurerIntegrationTests {
pvs = new MutablePropertyValues();
pvs.add("location", "${myprop}/test/${myprop}");
ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanInitializationException");
}
catch (BeanInitializationException ex) {
// expected
assertTrue(ex.getMessage().contains("myprop"));
}
assertThatExceptionOfType(BeanInitializationException.class).isThrownBy(
ac::refresh)
.withMessageContaining("myprop");
}
@Test
@@ -127,13 +109,8 @@ public class PropertyResourceConfigurerIntegrationTests {
pvs = new MutablePropertyValues();
pvs.add("properties", "var=${m}var\nm=${var2}\nvar2=${var}");
ac.registerSingleton("configurer1", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
}
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(
ac::refresh);
}
@Test
@@ -145,13 +122,8 @@ public class PropertyResourceConfigurerIntegrationTests {
pvs = new MutablePropertyValues();
pvs.add("properties", "var=${m}var\nm=${var2}\nvar2=${m}");
ac.registerSingleton("configurer1", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
}
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(
ac::refresh);
}
@Test
@@ -163,14 +135,8 @@ public class PropertyResourceConfigurerIntegrationTests {
pvs = new MutablePropertyValues();
pvs.add("properties", "var=${m}var\nm=${var2}\nvar2=${m2}");
ac.registerSingleton("configurer1", PropertyPlaceholderConfigurer.class, pvs);
try {
ac.refresh();
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
ex.printStackTrace();
}
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(
ac::refresh);
}
@Ignore // this test was breaking after the 3.0 repackaging

View File

@@ -33,6 +33,7 @@ import org.springframework.mock.env.MockEnvironment;
import org.springframework.mock.env.MockPropertySource;
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.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
@@ -154,7 +155,7 @@ public class PropertySourcesPlaceholderConfigurerTests {
assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}"));
}
@Test(expected = BeanDefinitionStoreException.class)
@Test
public void ignoreUnresolvablePlaceholders_falseIsDefault() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerBeanDefinition("testBean",
@@ -164,7 +165,8 @@ public class PropertySourcesPlaceholderConfigurerTests {
PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
//pc.setIgnoreUnresolvablePlaceholders(false); // the default
ppc.postProcessBeanFactory(bf); // should throw
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
ppc.postProcessBeanFactory(bf));
}
@Test
@@ -181,7 +183,7 @@ public class PropertySourcesPlaceholderConfigurerTests {
assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}"));
}
@Test(expected = BeanDefinitionStoreException.class)
@Test
@SuppressWarnings("serial")
public void nestedUnresolvablePlaceholder() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
@@ -194,7 +196,8 @@ public class PropertySourcesPlaceholderConfigurerTests {
ppc.setProperties(new Properties() {{
put("my.name", "${bogus}");
}});
ppc.postProcessBeanFactory(bf); // should throw
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() ->
ppc.postProcessBeanFactory(bf));
}
@Test

View File

@@ -29,10 +29,10 @@ import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@@ -193,16 +193,12 @@ public class ResourceBundleMessageSourceTests {
}
assertEquals("I'm", ac.getMessage("escaped", new Object[] {"some arg"}, Locale.ENGLISH));
try {
if (useCodeAsDefaultMessage) {
assertEquals("code4", ac.getMessage("code4", null, Locale.GERMAN));
if (!useCodeAsDefaultMessage) {
fail("Should have thrown NoSuchMessageException");
}
}
catch (NoSuchMessageException ex) {
if (useCodeAsDefaultMessage) {
fail("Should have returned code as default message");
}
else {
assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() ->
ac.getMessage("code4", null, Locale.GERMAN));
}
}
@@ -278,13 +274,8 @@ public class ResourceBundleMessageSourceTests {
ms.setBasename("org/springframework/context/support/messages");
ms.setDefaultEncoding("argh");
ms.setFallbackToSystemLocale(false);
try {
ms.getMessage("code1", null, Locale.ENGLISH);
fail("Should have thrown NoSuchMessageException");
}
catch (NoSuchMessageException ex) {
// expected
}
assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() ->
ms.getMessage("code1", null, Locale.ENGLISH));
}
@Test
@@ -363,13 +354,8 @@ public class ResourceBundleMessageSourceTests {
fileCharsets.setProperty("org/springframework/context/support/messages_de", "unicode");
ms.setFileEncodings(fileCharsets);
ms.setFallbackToSystemLocale(false);
try {
ms.getMessage("code1", null, Locale.ENGLISH);
fail("Should have thrown NoSuchMessageException");
}
catch (NoSuchMessageException ex) {
// expected
}
assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() ->
ms.getMessage("code1", null, Locale.ENGLISH));
}
@Test
@@ -380,13 +366,8 @@ public class ResourceBundleMessageSourceTests {
Properties fileCharsets = new Properties();
fileCharsets.setProperty("org/springframework/context/support/messages", "unicode");
ms.setFileEncodings(fileCharsets);
try {
ms.getMessage("code1", null, Locale.ENGLISH);
fail("Should have thrown NoSuchMessageException");
}
catch (NoSuchMessageException ex) {
// expected
}
assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() ->
ms.getMessage("code1", null, Locale.ENGLISH));
}
@Test

View File

@@ -153,10 +153,11 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests {
.equals("This is a test message in the message catalog with no args."));
}
@Test(expected = NoSuchMessageException.class)
@Test
public void getMessageWithNoDefaultPassedInAndNotFoundInMsgCatalog() {
// Try with Locale.US
sac.getMessage("bogus.message", null, Locale.US);
assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() ->
sac.getMessage("bogus.message", null, Locale.US));
}
@Test

View File

@@ -27,8 +27,9 @@ import org.junit.Test;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.jndi.JndiTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -72,13 +73,9 @@ public class LocalSlsbInvokerInterceptorTests {
// default resourceRef=false should cause this to fail, as java:/comp/env will not
// automatically be added
si.setJndiTemplate(jt);
try {
si.afterPropertiesSet();
fail("Should have failed with naming exception");
}
catch (NamingException ex) {
assertTrue(ex == nex);
}
assertThatExceptionOfType(NamingException.class).isThrownBy(
si::afterPropertiesSet)
.satisfies(ex -> assertThat(ex).isSameAs(nex));
}
@Test
@@ -136,13 +133,9 @@ public class LocalSlsbInvokerInterceptorTests {
pf.addAdvice(si);
LocalInterfaceWithBusinessMethods target = (LocalInterfaceWithBusinessMethods) pf.getProxy();
try {
target.targetMethod();
fail("Should have thrown exception");
}
catch (Exception thrown) {
assertTrue(thrown == expected);
}
assertThatExceptionOfType(Exception.class).isThrownBy(
target::targetMethod)
.satisfies(ex -> assertThat(ex).isSameAs(expected));
verify(mockContext).close();
}

View File

@@ -26,10 +26,10 @@ import org.junit.Test;
import org.springframework.jndi.JndiTemplate;
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.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.mockito.Mockito.verify;
@@ -139,13 +139,9 @@ public class LocalStatelessSessionProxyFactoryBeanTests {
MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject();
assertTrue(Proxy.isProxyClass(mbm.getClass()));
try {
mbm.getValue();
fail("Should have failed to create EJB");
}
catch (EjbAccessException ex) {
assertSame(cex, ex.getCause());
}
assertThatExceptionOfType(EjbAccessException.class).isThrownBy(
mbm::getValue)
.withCause(cex);
}
@Test
@@ -174,14 +170,9 @@ public class LocalStatelessSessionProxyFactoryBeanTests {
// Check it's a singleton
assertTrue(fb.isSingleton());
try {
fb.afterPropertiesSet();
fail("Should have failed to create EJB");
}
catch (IllegalArgumentException ex) {
// TODO more appropriate exception?
assertTrue(ex.getMessage().indexOf("businessInterface") != 1);
}
assertThatIllegalArgumentException().isThrownBy(
fb::afterPropertiesSet)
.withMessageContaining("businessInterface");
// Expect no methods on home
verifyZeroInteractions(home);

View File

@@ -30,9 +30,10 @@ import org.springframework.aop.framework.ProxyFactory;
import org.springframework.jndi.JndiTemplate;
import org.springframework.remoting.RemoteAccessException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -130,13 +131,9 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
// default resourceRef=false should cause this to fail, as java:/comp/env will not
// automatically be added
si.setJndiTemplate(jt);
try {
si.afterPropertiesSet();
fail("Should have failed with naming exception");
}
catch (NamingException ex) {
assertTrue(ex == nex);
}
assertThatExceptionOfType(NamingException.class).isThrownBy(
si::afterPropertiesSet)
.satisfies(ex -> assertThat(ex).isSameAs(nex));
}
@Test
@@ -199,13 +196,8 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
RemoteInterface target = (RemoteInterface) configuredProxy(si, RemoteInterface.class);
try {
target.targetMethod();
fail("Should have thrown RemoteException");
}
catch (RemoteException ex) {
// expected
}
assertThatExceptionOfType(RemoteException.class).isThrownBy(
target::targetMethod);
verify(mockContext).close();
verify(ejb, times(2)).remove();
@@ -254,13 +246,8 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
si.setCacheHome(cacheHome);
RemoteInterface target = (RemoteInterface) configuredProxy(si, RemoteInterface.class);
try {
target.targetMethod();
fail("Should have thrown RemoteException");
}
catch (ConnectException ex) {
// expected
}
assertThatExceptionOfType(ConnectException.class).isThrownBy(
target::targetMethod);
verify(mockContext, times(lookupCount)).close();
verify(ejb, times(2)).remove();
@@ -295,13 +282,8 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
BusinessInterface target = (BusinessInterface) configuredProxy(si, BusinessInterface.class);
try {
target.targetMethod();
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
assertThatExceptionOfType(RemoteAccessException.class).isThrownBy(
target::targetMethod);
verify(mockContext).close();
verify(ejb).remove();
@@ -327,14 +309,9 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
RemoteInterface target = (RemoteInterface) configuredProxy(si, RemoteInterface.class);
try {
target.targetMethod();
fail("Should have thrown remote exception");
}
catch (Exception thrown) {
assertTrue(thrown == expected);
}
assertThatExceptionOfType(Exception.class).isThrownBy(
target::targetMethod)
.satisfies(ex -> assertThat(ex).isSameAs(expected));
verify(mockContext).close();
verify(ejb).remove();
}

View File

@@ -28,10 +28,11 @@ import org.junit.Test;
import org.springframework.jndi.JndiTemplate;
import org.springframework.remoting.RemoteAccessException;
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.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.mockito.Mockito.verify;
@@ -157,13 +158,9 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject();
assertTrue(Proxy.isProxyClass(mbm.getClass()));
try {
mbm.getValue();
fail("Should've thrown remote exception");
}
catch (RemoteException ex) {
assertSame("Threw expected RemoteException", rex, ex);
}
assertThatExceptionOfType(RemoteException.class).isThrownBy(
mbm::getValue)
.satisfies(ex -> assertThat(ex).isSameAs(rex));
verify(myEjb).remove();
}
@@ -196,14 +193,7 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject();
assertTrue(Proxy.isProxyClass(mbm.getClass()));
try {
mbm.getValue();
fail("Should have failed to create EJB");
}
catch (RemoteException ex) {
// expected
}
assertThatExceptionOfType(RemoteException.class).isThrownBy(mbm::getValue);
}
@Test
@@ -235,14 +225,9 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
MyLocalBusinessMethods mbm = (MyLocalBusinessMethods) fb.getObject();
assertTrue(Proxy.isProxyClass(mbm.getClass()));
try {
mbm.getValue();
fail("Should have failed to create EJB");
}
catch (RemoteAccessException ex) {
assertTrue(ex.getCause() == cex);
}
assertThatExceptionOfType(RemoteAccessException.class).isThrownBy(
mbm::getValue)
.withCause(cex);
}
@Test
@@ -271,14 +256,9 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
// Check it's a singleton
assertTrue(fb.isSingleton());
try {
fb.afterPropertiesSet();
fail("Should have failed to create EJB");
}
catch (IllegalArgumentException ex) {
// TODO more appropriate exception?
assertTrue(ex.getMessage().indexOf("businessInterface") != 1);
}
assertThatIllegalArgumentException().isThrownBy(
fb::afterPropertiesSet)
.withMessageContaining("businessInterface");
// Expect no methods on home
verifyZeroInteractions(home);

View File

@@ -23,6 +23,7 @@ import java.util.Locale;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
/**
@@ -43,9 +44,10 @@ public class CurrencyStyleFormatterTests {
assertEquals(new BigDecimal("23.56"), formatter.parse("$23.56", Locale.US));
}
@Test(expected = ParseException.class)
@Test
public void parseBogusValue() throws ParseException {
formatter.parse("bogus", Locale.US);
assertThatExceptionOfType(ParseException.class).isThrownBy(() ->
formatter.parse("bogus", Locale.US));
}
@Test
@@ -59,9 +61,10 @@ public class CurrencyStyleFormatterTests {
assertEquals(new BigDecimal("23.00"), formatter.parse("$23", Locale.US));
}
@Test(expected = ParseException.class)
@Test
public void parseValueNotLenientFailure() throws ParseException {
formatter.parse("$23.56bogus", Locale.US);
assertThatExceptionOfType(ParseException.class).isThrownBy(() ->
formatter.parse("$23.56bogus", Locale.US));
}
}

View File

@@ -22,6 +22,7 @@ import java.util.Locale;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
/**
@@ -42,14 +43,16 @@ public class NumberStyleFormatterTests {
assertEquals(new BigDecimal("23.56"), formatter.parse("23.56", Locale.US));
}
@Test(expected = ParseException.class)
@Test
public void parseBogusValue() throws ParseException {
formatter.parse("bogus", Locale.US);
assertThatExceptionOfType(ParseException.class).isThrownBy(() ->
formatter.parse("bogus", Locale.US));
}
@Test(expected = ParseException.class)
@Test
public void parsePercentValueNotLenientFailure() throws ParseException {
formatter.parse("23.56bogus", Locale.US);
assertThatExceptionOfType(ParseException.class).isThrownBy(() ->
formatter.parse("23.56bogus", Locale.US));
}
}

View File

@@ -22,6 +22,7 @@ import java.util.Locale;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
/**
@@ -42,14 +43,16 @@ public class PercentStyleFormatterTests {
assertEquals(new BigDecimal(".2356"), formatter.parse("23.56%", Locale.US));
}
@Test(expected = ParseException.class)
@Test
public void parseBogusValue() throws ParseException {
formatter.parse("bogus", Locale.US);
assertThatExceptionOfType(ParseException.class).isThrownBy(() ->
formatter.parse("bogus", Locale.US));
}
@Test(expected = ParseException.class)
@Test
public void parsePercentValueNotLenientFailure() throws ParseException {
formatter.parse("23.56%bogus", Locale.US);
assertThatExceptionOfType(ParseException.class).isThrownBy(() ->
formatter.parse("23.56%bogus", Locale.US));
}
}

View File

@@ -39,9 +39,9 @@ import org.springframework.format.Parser;
import org.springframework.format.Printer;
import org.springframework.format.annotation.NumberFormat;
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.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rossen Stoyanchev
@@ -76,13 +76,9 @@ public class FormattingConversionServiceFactoryBeanTests {
FormattingConversionService fcs = factory.getObject();
TypeDescriptor descriptor = new TypeDescriptor(TestBean.class.getDeclaredField("pattern"));
try {
fcs.convert("15,00", TypeDescriptor.valueOf(String.class), descriptor);
fail("This format should not be parseable");
}
catch (ConversionFailedException ex) {
assertTrue(ex.getCause() instanceof NumberFormatException);
}
assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() ->
fcs.convert("15,00", TypeDescriptor.valueOf(String.class), descriptor))
.withCauseInstanceOf(NumberFormatException.class);
}
@Test
@@ -126,13 +122,7 @@ public class FormattingConversionServiceFactoryBeanTests {
Set<Object> formatters = new HashSet<>();
formatters.add(new Object());
factory.setFormatters(formatters);
try {
factory.afterPropertiesSet();
fail("Expected formatter to be rejected");
}
catch (IllegalArgumentException ex) {
// expected
}
assertThatIllegalArgumentException().isThrownBy(factory::afterPropertiesSet);
}

View File

@@ -55,6 +55,7 @@ import org.springframework.format.datetime.joda.JodaDateTimeFormatAnnotationForm
import org.springframework.format.datetime.joda.ReadablePartialPrinter;
import org.springframework.format.number.NumberStyleFormatter;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@@ -265,16 +266,18 @@ public class FormattingConversionServiceTests {
assertNull(formattingService.convert(" ", TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class)));
}
@Test(expected = ConversionFailedException.class)
@Test
public void parseParserReturnsNull() throws ParseException {
formattingService.addFormatterForFieldType(Integer.class, new NullReturningFormatter());
assertNull(formattingService.convert("1", TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class)));
assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() ->
formattingService.convert("1", TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class)));
}
@Test(expected = ConversionFailedException.class)
@Test
public void parseNullPrimitiveProperty() throws ParseException {
formattingService.addFormatterForFieldType(Integer.class, new NumberStyleFormatter());
assertNull(formattingService.convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(int.class)));
assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() ->
formattingService.convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(int.class)));
}
@Test

View File

@@ -21,6 +21,8 @@ import java.security.ProtectionDomain;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@@ -32,14 +34,16 @@ import static org.junit.Assert.assertNotNull;
*/
public class ReflectiveLoadTimeWeaverTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWithNullClassLoader() {
new ReflectiveLoadTimeWeaver(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new ReflectiveLoadTimeWeaver(null));
}
@Test(expected = IllegalStateException.class)
@Test
public void testCtorWithClassLoaderThatDoesNotExposeAnAddTransformerMethod() {
new ReflectiveLoadTimeWeaver(getClass().getClassLoader());
assertThatIllegalStateException().isThrownBy(() ->
new ReflectiveLoadTimeWeaver(getClass().getClassLoader()));
}
@Test
@@ -55,9 +59,10 @@ public class ReflectiveLoadTimeWeaverTests {
assertEquals(1, classLoader.getNumTimesGetThrowawayClassLoaderCalled());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testAddTransformerWithNullTransformer() {
new ReflectiveLoadTimeWeaver(new JustAddTransformerClassLoader()).addTransformer(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new ReflectiveLoadTimeWeaver(new JustAddTransformerClassLoader()).addTransformer(null));
}
@Test

View File

@@ -17,7 +17,6 @@
package org.springframework.jmx.access;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.BindException;
import java.util.HashMap;
@@ -38,6 +37,9 @@ import org.springframework.jmx.export.MBeanExporter;
import org.springframework.jmx.export.assembler.AbstractReflectiveMBeanInfoAssembler;
import org.springframework.util.SocketUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
@@ -119,32 +121,36 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests {
assertEquals("The name of the bean should have been updated", "Rob Harrop", target.getName());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSetAttributeValueWithRuntimeException() throws Exception {
assumeTrue(runTests);
IJmxTestBean proxy = getProxy();
proxy.setName("Juergen");
assertThatIllegalArgumentException().isThrownBy(() ->
proxy.setName("Juergen"));
}
@Test(expected = ClassNotFoundException.class)
@Test
public void testSetAttributeValueWithCheckedException() throws Exception {
assumeTrue(runTests);
IJmxTestBean proxy = getProxy();
proxy.setName("Juergen Class");
assertThatExceptionOfType(ClassNotFoundException.class).isThrownBy(() ->
proxy.setName("Juergen Class"));
}
@Test(expected = IOException.class)
@Test
public void testSetAttributeValueWithIOException() throws Exception {
assumeTrue(runTests);
IJmxTestBean proxy = getProxy();
proxy.setName("Juergen IO");
assertThatIOException().isThrownBy(() ->
proxy.setName("Juergen IO"));
}
@Test(expected = InvalidInvocationException.class)
@Test
public void testSetReadOnlyAttribute() throws Exception {
assumeTrue(runTests);
IJmxTestBean proxy = getProxy();
proxy.setAge(900);
assertThatExceptionOfType(InvalidInvocationException.class).isThrownBy(() ->
proxy.setAge(900));
}
@Test
@@ -163,11 +169,12 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests {
assertEquals("The operation should return 3", 3, result);
}
@Test(expected = InvalidInvocationException.class)
@Test
public void testInvokeUnexposedMethodWithException() throws Exception {
assumeTrue(runTests);
IJmxTestBean bean = getProxy();
bean.dontExposeMe();
assertThatExceptionOfType(InvalidInvocationException.class).isThrownBy(() ->
bean.dontExposeMe());
}
@Test

View File

@@ -30,8 +30,8 @@ import org.springframework.jmx.JmxTestBean;
import org.springframework.jmx.export.naming.ObjectNamingStrategy;
import org.springframework.jmx.support.ObjectNameManager;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@@ -114,13 +114,9 @@ public class MBeanExporterOperationsTests extends AbstractMBeanServerTests {
ObjectName reg1 = exporter.registerManagedResource(bean1);
assertIsRegistered("Bean 1 not registered with MBeanServer", reg1);
try {
exporter.registerManagedResource(bean2);
fail("Shouldn't be able to register a runtime MBean with a reused ObjectName.");
}
catch (MBeanExportException e) {
assertEquals("Incorrect root cause", InstanceAlreadyExistsException.class, e.getCause().getClass());
}
assertThatExceptionOfType(MBeanExportException.class).isThrownBy(()->
exporter.registerManagedResource(bean2))
.withCauseExactlyInstanceOf(InstanceAlreadyExistsException.class);
}
private void assertObjectNameMatchesTemplate(ObjectName objectNameTemplate, ObjectName registeredName) {

View File

@@ -55,13 +55,12 @@ import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.tests.aop.interceptor.NopInterceptor;
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.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Integration tests for the {@link MBeanExporter} class.
@@ -105,14 +104,9 @@ public class MBeanExporterTests extends AbstractMBeanServerTests {
exporter.setBeans(getBeanMap());
exporter.setServer(server);
exporter.setNotificationListenerMappings(listeners);
try {
start(exporter);
fail("Must have thrown an MBeanExportException when registering a " +
"NotificationListener on a non-existent MBean.");
}
catch (MBeanExportException expected) {
assertTrue(expected.contains(InstanceNotFoundException.class));
}
assertThatExceptionOfType(MBeanExportException.class).as("NotificationListener on a non-existent MBean").isThrownBy(() ->
start(exporter))
.satisfies(ex -> assertThat(ex.contains(InstanceNotFoundException.class)));
}
@Test
@@ -617,12 +611,8 @@ public class MBeanExporterTests extends AbstractMBeanServerTests {
exporter.setBeans(beansToExport);
exporter.setBeanFactory(factory);
try {
start(exporter);
fail("Must have failed during creation of RuntimeExceptionThrowingConstructorBean");
}
catch (RuntimeException expected) {
}
assertThatExceptionOfType(RuntimeException.class).as("failed during creation of RuntimeExceptionThrowingConstructorBean").isThrownBy(() ->
start(exporter));
assertIsNotRegistered("Must have unregistered all previously registered MBeans due to RuntimeException",
ObjectNameManager.getInstance(objectName1));

View File

@@ -35,8 +35,8 @@ import org.springframework.jmx.access.NotificationListenerRegistrar;
import org.springframework.jmx.export.naming.SelfNaming;
import org.springframework.jmx.support.ObjectNameManager;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@@ -199,12 +199,8 @@ public class NotificationListenerTests extends AbstractMBeanServerTests {
@Test
public void testCreationWithNoNotificationListenerSet() {
try {
new NotificationListenerBean().afterPropertiesSet();
fail("Must have thrown an IllegalArgumentException (no NotificationListener supplied)");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().as("no NotificationListener supplied").isThrownBy(
new NotificationListenerBean()::afterPropertiesSet);
}
@SuppressWarnings({ "rawtypes", "unchecked" })

View File

@@ -23,10 +23,10 @@ import javax.management.modelmbean.ModelMBeanInfo;
import org.junit.Test;
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.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@@ -47,24 +47,14 @@ public class InterfaceBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAsse
@Test
public void testWithUnknownClass() throws Exception {
try {
getWithMapping("com.foo.bar.Unknown");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
assertThatIllegalArgumentException().isThrownBy(() ->
getWithMapping("com.foo.bar.Unknown"));
}
@Test
public void testWithNonInterface() throws Exception {
try {
getWithMapping("JmxTestBean");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
assertThatIllegalArgumentException().isThrownBy(() ->
getWithMapping("JmxTestBean"));
}
@Test

View File

@@ -27,6 +27,7 @@ import org.junit.Test;
import org.springframework.jmx.export.SpringModelMBean;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
@@ -37,26 +38,30 @@ import static org.junit.Assert.assertTrue;
*/
public class ModelMBeanNotificationPublisherTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWithNullMBean() throws Exception {
new ModelMBeanNotificationPublisher(null, createObjectName(), this);
assertThatIllegalArgumentException().isThrownBy(() ->
new ModelMBeanNotificationPublisher(null, createObjectName(), this));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWithNullObjectName() throws Exception {
new ModelMBeanNotificationPublisher(new SpringModelMBean(), null, this);
assertThatIllegalArgumentException().isThrownBy(() ->
new ModelMBeanNotificationPublisher(new SpringModelMBean(), null, this));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCtorWithNullManagedResource() throws Exception {
new ModelMBeanNotificationPublisher(new SpringModelMBean(), createObjectName(), null);
assertThatIllegalArgumentException().isThrownBy(() ->
new ModelMBeanNotificationPublisher(new SpringModelMBean(), createObjectName(), null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSendNullNotification() throws Exception {
NotificationPublisher publisher
= new ModelMBeanNotificationPublisher(new SpringModelMBean(), createObjectName(), this);
publisher.sendNotification(null);
assertThatIllegalArgumentException().isThrownBy(() ->
publisher.sendNotification(null));
}
public void testSendVanillaNotification() throws Exception {

View File

@@ -31,9 +31,9 @@ import org.junit.Test;
import org.springframework.jmx.AbstractMBeanServerTests;
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 Rob Harrop
@@ -99,14 +99,10 @@ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests {
public void noRegisterWithMBeanServer() throws Exception {
ConnectorServerFactoryBean bean = new ConnectorServerFactoryBean();
bean.afterPropertiesSet();
try {
// Try to get the connector bean.
getServer().getObjectInstance(ObjectName.getInstance(OBJECT_NAME));
fail("Instance should not be found");
}
catch (InstanceNotFoundException ex) {
// expected
assertThatExceptionOfType(InstanceNotFoundException.class).isThrownBy(() ->
getServer().getObjectInstance(ObjectName.getInstance(OBJECT_NAME)));
}
finally {
bean.destroy();

View File

@@ -28,6 +28,7 @@ import org.springframework.aop.support.AopUtils;
import org.springframework.jmx.AbstractMBeanServerTests;
import org.springframework.util.SocketUtils;
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;
@@ -76,10 +77,11 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe
}
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithNoServiceUrl() throws Exception {
MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean();
bean.afterPropertiesSet();
assertThatIllegalArgumentException().isThrownBy(
bean::afterPropertiesSet);
}
@Test

View File

@@ -27,10 +27,10 @@ import org.junit.Test;
import org.springframework.util.MBeanTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
/**
* @author Rob Harrop
@@ -138,26 +138,23 @@ public class MBeanServerFactoryBeanTests {
MBeanServerFactoryBean bean = new MBeanServerFactoryBean();
bean.setRegisterWithFactory(referenceShouldExist);
bean.afterPropertiesSet();
try {
MBeanServer server = bean.getObject();
List<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
boolean found = false;
for (MBeanServer candidate : servers) {
if (candidate == server) {
found = true;
break;
}
}
if (!(found == referenceShouldExist)) {
fail(failMsg);
}
assertThat(hasInstance(servers, server)).as(failMsg).isEqualTo(referenceShouldExist);
}
finally {
bean.destroy();
}
}
private boolean hasInstance(List<MBeanServer> servers, MBeanServer server) {
for (MBeanServer candidate : servers) {
if (candidate == server) {
return true;
}
}
return false;
}
}

View File

@@ -27,10 +27,12 @@ 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.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -46,12 +48,7 @@ public class JndiObjectFactoryBeanTests {
@Test
public void testNoJndiName() throws NamingException {
JndiObjectFactoryBean jof = new JndiObjectFactoryBean();
try {
jof.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
}
assertThatIllegalArgumentException().isThrownBy(jof::afterPropertiesSet);
}
@Test
@@ -116,13 +113,7 @@ public class JndiObjectFactoryBeanTests {
jof.setJndiTemplate(new ExpectedLookupTemplate("java:comp/env/foo", o));
jof.setJndiName("foo");
jof.setResourceRef(false);
try {
jof.afterPropertiesSet();
fail("Should have thrown NamingException");
}
catch (NamingException ex) {
// expected
}
assertThatExceptionOfType(NamingException.class).isThrownBy(jof::afterPropertiesSet);
}
@Test
@@ -153,13 +144,9 @@ public class JndiObjectFactoryBeanTests {
jof.setJndiTemplate(new ExpectedLookupTemplate("foo", new Object()));
jof.setJndiName("foo");
jof.setExpectedType(String.class);
try {
jof.afterPropertiesSet();
fail("Should have thrown NamingException");
}
catch (NamingException ex) {
assertTrue(ex.getMessage().contains("java.lang.String"));
}
assertThatExceptionOfType(NamingException.class).isThrownBy(
jof::afterPropertiesSet)
.withMessageContaining("java.lang.String");
}
@Test
@@ -214,13 +201,7 @@ public class JndiObjectFactoryBeanTests {
jof.setJndiName("myFoo");
jof.setExpectedType(Boolean.class);
jof.setDefaultObject("5");
try {
jof.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
assertThatIllegalArgumentException().isThrownBy(jof::afterPropertiesSet);
}
@Test
@@ -246,13 +227,7 @@ public class JndiObjectFactoryBeanTests {
jof.setJndiName("myFoo");
jof.setProxyInterface(ITestBean.class);
jof.setDefaultObject(Boolean.TRUE);
try {
jof.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
assertThatIllegalArgumentException().isThrownBy(jof::afterPropertiesSet);
}
@Test
@@ -349,13 +324,7 @@ public class JndiObjectFactoryBeanTests {
JndiObjectFactoryBean jof = new JndiObjectFactoryBean();
jof.setJndiName("foo");
jof.setLookupOnStartup(false);
try {
jof.afterPropertiesSet();
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(jof::afterPropertiesSet);
}
@Test
@@ -364,13 +333,7 @@ public class JndiObjectFactoryBeanTests {
jof.setJndiName("foo");
jof.setCache(false);
jof.setLookupOnStartup(false);
try {
jof.afterPropertiesSet();
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(jof::afterPropertiesSet);
}
@Test
@@ -397,13 +360,9 @@ public class JndiObjectFactoryBeanTests {
jof.setJndiName("foo");
jof.setExpectedType(DerivedTestBean.class);
jof.setProxyInterface(ITestBean.class);
try {
jof.afterPropertiesSet();
fail("Should have thrown NamingException");
}
catch (NamingException ex) {
assertTrue(ex.getMessage().contains("org.springframework.tests.sample.beans.DerivedTestBean"));
}
assertThatExceptionOfType(NamingException.class).isThrownBy(
jof::afterPropertiesSet)
.withMessageContaining("org.springframework.tests.sample.beans.DerivedTestBean");
}
@Test

View File

@@ -18,8 +18,8 @@ package org.springframework.jndi;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rod Johnson
@@ -29,13 +29,8 @@ public class JndiTemplateEditorTests {
@Test
public void testNullIsIllegalArgument() {
try {
new JndiTemplateEditor().setAsText(null);
fail("Null is illegal");
}
catch (IllegalArgumentException ex) {
// OK
}
assertThatIllegalArgumentException().isThrownBy(() ->
new JndiTemplateEditor().setAsText(null));
}
@Test

View File

@@ -21,8 +21,8 @@ import javax.naming.NameNotFoundException;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -68,13 +68,8 @@ public class JndiTemplateTests {
}
};
try {
jt.lookup(name);
fail("Should have thrown NamingException");
}
catch (NameNotFoundException ex) {
// Ok
}
assertThatExceptionOfType(NameNotFoundException.class).isThrownBy(() ->
jt.lookup(name));
verify(context).close();
}
@@ -91,13 +86,8 @@ public class JndiTemplateTests {
}
};
try {
jt.lookup(name);
fail("Should have thrown NamingException");
}
catch (NameNotFoundException ex) {
// Ok
}
assertThatExceptionOfType(NameNotFoundException.class).isThrownBy(() ->
jt.lookup(name));
verify(context).close();
}
@@ -115,13 +105,8 @@ public class JndiTemplateTests {
}
};
try {
jt.lookup(name, String.class);
fail("Should have thrown TypeMismatchNamingException");
}
catch (TypeMismatchNamingException ex) {
// Ok
}
assertThatExceptionOfType(TypeMismatchNamingException.class).isThrownBy(() ->
jt.lookup(name, String.class));
verify(context).close();
}

View File

@@ -38,9 +38,9 @@ import org.junit.Test;
import org.springframework.tests.mock.jndi.SimpleNamingContext;
import org.springframework.tests.mock.jndi.SimpleNamingContextBuilder;
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
@@ -86,35 +86,20 @@ public class SimpleNamingContextTests {
assertTrue("key1 removed", context3.getEnvironment().get("key1") == null);
assertTrue("Correct DataSource registered", context1.lookup("jdbc/myds") == ds);
try {
context1.lookup("myobject");
fail("Should have thrown NameNotFoundException");
}
catch (NameNotFoundException ex) {
// expected
}
assertThatExceptionOfType(NameNotFoundException.class).isThrownBy(() ->
context1.lookup("myobject"));
assertTrue("Correct Integer registered", context1.lookup("myinteger") == i);
assertTrue("Correct String registered", context1.lookup("mystring") == s);
assertTrue("Correct DataSource registered", context2.lookup("jdbc/myds") == ds);
try {
context2.lookup("myobject");
fail("Should have thrown NameNotFoundException");
}
catch (NameNotFoundException ex) {
// expected
}
assertThatExceptionOfType(NameNotFoundException.class).isThrownBy(() ->
context2.lookup("myobject"));
assertTrue("Correct Integer registered", context2.lookup("myinteger") == i);
assertTrue("Correct String registered", context2.lookup("mystring") == s);
assertTrue("Correct DataSource registered", context3.lookup("jdbc/myds") == ds);
try {
context3.lookup("myobject");
fail("Should have thrown NameNotFoundException");
}
catch (NameNotFoundException ex) {
// expected
}
assertThatExceptionOfType(NameNotFoundException.class).isThrownBy(() ->
context3.lookup("myobject"));
assertTrue("Correct Integer registered", context3.lookup("myinteger") == i);
assertTrue("Correct String registered", context3.lookup("mystring") == s);
@@ -192,28 +177,18 @@ public class SimpleNamingContextTests {
assertTrue(ctx.lookup(name) == o);
// Check it returns mutable contexts
ctx.unbind(name);
try {
ctx = new InitialContext();
ctx.lookup(name);
fail("Should have thrown NamingException");
}
catch (NamingException ex) {
// expected
}
InitialContext badCtx1 = new InitialContext();
assertThatExceptionOfType(NamingException.class).isThrownBy(() ->
badCtx1.lookup(name));
// Check the same call will work again, but the context is empty
builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
try {
ctx = new InitialContext();
ctx.lookup(name);
fail("Should have thrown NamingException");
}
catch (NamingException ex) {
// expected
}
InitialContext badCtx2 = new InitialContext();
assertThatExceptionOfType(NamingException.class).isThrownBy(() ->
badCtx2.lookup(name));
Object o2 = new Object();
builder.bind(name, o2);
assertEquals(ctx.lookup(name), o2);
assertEquals(badCtx2.lookup(name), o2);
}

View File

@@ -37,10 +37,12 @@ import org.springframework.remoting.RemoteConnectFailureException;
import org.springframework.remoting.RemoteProxyFailureException;
import org.springframework.remoting.support.RemoteInvocation;
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.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@@ -102,25 +104,15 @@ public class RmiSupportTests {
doTestRmiProxyFactoryBeanWithException(UnmarshalException.class);
}
private void doTestRmiProxyFactoryBeanWithException(Class<?> exceptionClass) throws Exception {
private void doTestRmiProxyFactoryBeanWithException(Class<? extends Throwable> exceptionClass) throws Exception {
CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean();
factory.setServiceInterface(IRemoteBean.class);
factory.setServiceUrl("rmi://localhost:1090/test");
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
try {
proxy.setName(exceptionClass.getName());
fail("Should have thrown " + exceptionClass.getName());
}
catch (Exception ex) {
if (exceptionClass.isInstance(ex)) {
// expected
}
else {
throw ex;
}
}
assertThatExceptionOfType(exceptionClass).isThrownBy(() ->
proxy.setName(exceptionClass.getName()));
assertEquals(1, factory.counter);
}
@@ -149,7 +141,7 @@ public class RmiSupportTests {
doTestRmiProxyFactoryBeanWithExceptionAndRefresh(StubNotFoundException.class);
}
private void doTestRmiProxyFactoryBeanWithExceptionAndRefresh(Class<?> exceptionClass) throws Exception {
private void doTestRmiProxyFactoryBeanWithExceptionAndRefresh(Class<? extends Throwable> exceptionClass) throws Exception {
CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean();
factory.setServiceInterface(IRemoteBean.class);
factory.setServiceUrl("rmi://localhost:1090/test");
@@ -157,18 +149,8 @@ public class RmiSupportTests {
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
try {
proxy.setName(exceptionClass.getName());
fail("Should have thrown " + exceptionClass.getName());
}
catch (Exception ex) {
if (exceptionClass.isInstance(ex)) {
// expected
}
else {
throw ex;
}
}
assertThatExceptionOfType(exceptionClass).isThrownBy(() ->
proxy.setName(exceptionClass.getName()));
assertEquals(2, factory.counter);
}
@@ -195,15 +177,11 @@ public class RmiSupportTests {
assertTrue(factory.getObject() instanceof IWrongBusinessBean);
IWrongBusinessBean proxy = (IWrongBusinessBean) factory.getObject();
assertFalse(proxy instanceof IRemoteBean);
try {
proxy.setOtherName("name");
fail("Should have thrown RemoteProxyFailureException");
}
catch (RemoteProxyFailureException ex) {
assertTrue(ex.getCause() instanceof NoSuchMethodException);
assertTrue(ex.getMessage().contains("setOtherName"));
assertTrue(ex.getMessage().contains("IWrongBusinessBean"));
}
assertThatExceptionOfType(RemoteProxyFailureException.class).isThrownBy(() ->
proxy.setOtherName("name"))
.withCauseInstanceOf(NoSuchMethodException.class)
.withMessageContaining("setOtherName")
.withMessageContaining("IWrongBusinessBean");
assertEquals(1, factory.counter);
}
@@ -244,7 +222,7 @@ public class RmiSupportTests {
}
private void doTestRmiProxyFactoryBeanWithBusinessInterfaceAndException(
Class<?> rmiExceptionClass, Class<?> springExceptionClass) throws Exception {
Class<?> rmiExceptionClass, Class<? extends Throwable> springExceptionClass) throws Exception {
CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean();
factory.setServiceInterface(IBusinessBean.class);
@@ -253,18 +231,8 @@ public class RmiSupportTests {
assertTrue(factory.getObject() instanceof IBusinessBean);
IBusinessBean proxy = (IBusinessBean) factory.getObject();
assertFalse(proxy instanceof IRemoteBean);
try {
proxy.setName(rmiExceptionClass.getName());
fail("Should have thrown " + rmiExceptionClass.getName());
}
catch (Exception ex) {
if (springExceptionClass.isInstance(ex)) {
// expected
}
else {
throw ex;
}
}
assertThatExceptionOfType(springExceptionClass).isThrownBy(() ->
proxy.setName(rmiExceptionClass.getName()));
assertEquals(1, factory.counter);
}
@@ -305,7 +273,7 @@ public class RmiSupportTests {
}
private void doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefresh(
Class<?> rmiExceptionClass, Class<?> springExceptionClass) throws Exception {
Class<?> rmiExceptionClass, Class<? extends Throwable> springExceptionClass) throws Exception {
CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean();
factory.setServiceInterface(IBusinessBean.class);
@@ -315,38 +283,17 @@ public class RmiSupportTests {
assertTrue(factory.getObject() instanceof IBusinessBean);
IBusinessBean proxy = (IBusinessBean) factory.getObject();
assertFalse(proxy instanceof IRemoteBean);
try {
proxy.setName(rmiExceptionClass.getName());
fail("Should have thrown " + rmiExceptionClass.getName());
}
catch (Exception ex) {
if (springExceptionClass.isInstance(ex)) {
// expected
}
else {
throw ex;
}
}
if (RemoteConnectFailureException.class.isAssignableFrom(springExceptionClass)) {
assertEquals(2, factory.counter);
}
else {
assertEquals(1, factory.counter);
}
assertThatExceptionOfType(springExceptionClass).isThrownBy(() ->
proxy.setName(rmiExceptionClass.getName()));
boolean isRemoteConnectFaiure = RemoteConnectFailureException.class.isAssignableFrom(springExceptionClass);
assertThat(factory.counter).isEqualTo(isRemoteConnectFaiure ? 2 : 1);
}
@Test
public void rmiClientInterceptorRequiresUrl() throws Exception{
RmiClientInterceptor client = new RmiClientInterceptor();
client.setServiceInterface(IRemoteBean.class);
try {
client.afterPropertiesSet();
fail("url isn't set, expected IllegalArgumentException");
}
catch (IllegalArgumentException ex){
// expected
}
assertThatIllegalArgumentException().isThrownBy(client::afterPropertiesSet);
}
@Test
@@ -430,13 +377,8 @@ public class RmiSupportTests {
assertTrue(proxy.equals(proxy));
// should go through
try {
proxy.setName("test");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
assertThatExceptionOfType(RemoteAccessException.class).isThrownBy(() ->
proxy.setName("test"));
}

View File

@@ -42,11 +42,10 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.concurrent.ListenableFuture;
import static org.junit.Assert.assertEquals;
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.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Mark Fisher
@@ -220,17 +219,9 @@ public class AsyncAnnotationBeanPostProcessorTests {
private void assertFutureWithException(Future<Object> result,
TestableAsyncUncaughtExceptionHandler exceptionHandler) {
try {
result.get();
}
catch (InterruptedException ex) {
fail("Should not have failed with InterruptedException: " + ex);
}
catch (ExecutionException ex) {
// expected
assertEquals("Wrong exception cause", UnsupportedOperationException.class, ex.getCause().getClass());
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
result::get)
.withCauseExactlyInstanceOf(UnsupportedOperationException.class);
assertFalse("handler should never be called with Future return type", exceptionHandler.isCalled());
}
@@ -264,13 +255,8 @@ public class AsyncAnnotationBeanPostProcessorTests {
ITestBean testBean = context.getBean("target", ITestBean.class);
assertFalse("Handler should not have been called", exceptionHandler.isCalled());
try {
testBean.failWithVoid();
exceptionHandler.assertCalledWith(m, UnsupportedOperationException.class);
}
catch (Exception e) {
fail("No unexpected exception should have been received");
}
testBean.failWithVoid();
exceptionHandler.assertCalledWith(m, UnsupportedOperationException.class);
}
private ConfigurableApplicationContext initContext(BeanDefinition asyncAnnotationBeanPostProcessorDefinition) {

View File

@@ -43,9 +43,9 @@ import org.springframework.context.support.GenericApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;
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
@@ -80,45 +80,25 @@ public class AsyncExecutionTests {
CompletableFuture<String> completableFuture = asyncTest.returnSomethingCompletable(20);
assertEquals("20", completableFuture.get());
try {
asyncTest.returnSomething(0).get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex) {
assertTrue(ex.getCause() instanceof IllegalArgumentException);
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(() ->
asyncTest.returnSomething(0).get())
.withCauseInstanceOf(IllegalArgumentException.class);
try {
asyncTest.returnSomething(-1).get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(() ->
asyncTest.returnSomething(-1).get())
.withCauseInstanceOf(IOException.class);
try {
asyncTest.returnSomethingListenable(0).get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex) {
assertTrue(ex.getCause() instanceof IllegalArgumentException);
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(() ->
asyncTest.returnSomethingListenable(0).get())
.withCauseInstanceOf(IllegalArgumentException.class);
try {
asyncTest.returnSomethingListenable(-1).get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(() ->
asyncTest.returnSomethingListenable(-1).get())
.withCauseInstanceOf(IOException.class);
try {
asyncTest.returnSomethingCompletable(0).get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex) {
assertTrue(ex.getCause() instanceof IllegalArgumentException);
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(() ->
asyncTest.returnSomethingCompletable(0).get())
.withCauseInstanceOf(IllegalArgumentException.class);
}
@Test
@@ -197,29 +177,17 @@ public class AsyncExecutionTests {
CompletableFuture<String> completableFuture = asyncTest.returnSomethingCompletable(20);
assertEquals("20", completableFuture.get());
try {
asyncTest.returnSomething(0).get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex) {
assertTrue(ex.getCause() instanceof IllegalArgumentException);
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(() ->
asyncTest.returnSomething(0).get())
.withCauseInstanceOf(IllegalArgumentException.class);
try {
asyncTest.returnSomethingListenable(0).get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex) {
assertTrue(ex.getCause() instanceof IllegalArgumentException);
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(() ->
asyncTest.returnSomethingListenable(0).get())
.withCauseInstanceOf(IllegalArgumentException.class);
try {
asyncTest.returnSomethingCompletable(0).get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex) {
assertTrue(ex.getCause() instanceof IllegalArgumentException);
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(() ->
asyncTest.returnSomethingCompletable(0).get())
.withCauseInstanceOf(IllegalArgumentException.class);
}
@Test

View File

@@ -26,8 +26,8 @@ import org.junit.Test;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@@ -46,7 +46,7 @@ public class AsyncResultTests {
}
@Override
public void onFailure(Throwable ex) {
fail("Failure callback not expected: " + ex);
throw new AssertionError("Failure callback not expected: " + ex, ex);
}
});
assertSame(value, values.iterator().next());
@@ -63,7 +63,7 @@ public class AsyncResultTests {
future.addCallback(new ListenableFutureCallback<String>() {
@Override
public void onSuccess(String result) {
fail("Success callback not expected: " + result);
throw new AssertionError("Success callback not expected: " + result);
}
@Override
public void onFailure(Throwable ex) {
@@ -71,20 +71,12 @@ public class AsyncResultTests {
}
});
assertSame(ex, values.iterator().next());
try {
future.get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex2) {
assertSame(ex, ex2.getCause());
}
try {
future.completable().get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex2) {
assertSame(ex, ex2.getCause());
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
future::get)
.withCause(ex);
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
future.completable()::get)
.withCause(ex);
}
@Test
@@ -92,7 +84,7 @@ public class AsyncResultTests {
String value = "val";
final Set<String> values = new HashSet<>(1);
ListenableFuture<String> future = AsyncResult.forValue(value);
future.addCallback(values::add, ex -> fail("Failure callback not expected: " + ex));
future.addCallback(values::add, ex -> new AssertionError("Failure callback not expected: " + ex));
assertSame(value, values.iterator().next());
assertSame(value, future.get());
assertSame(value, future.completable().get());
@@ -104,22 +96,14 @@ public class AsyncResultTests {
IOException ex = new IOException();
final Set<Throwable> values = new HashSet<>(1);
ListenableFuture<String> future = AsyncResult.forExecutionException(ex);
future.addCallback(result -> fail("Success callback not expected: " + result), values::add);
future.addCallback(result -> new AssertionError("Success callback not expected: " + result), values::add);
assertSame(ex, values.iterator().next());
try {
future.get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex2) {
assertSame(ex, ex2.getCause());
}
try {
future.completable().get();
fail("Should have thrown ExecutionException");
}
catch (ExecutionException ex2) {
assertSame(ex, ex2.getCause());
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
future::get)
.withCause(ex);
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
future.completable()::get)
.withCause(ex);
}
}

View File

@@ -54,15 +54,14 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests use of @EnableAsync on @Configuration classes.
@@ -102,14 +101,9 @@ public class EnableAsyncTests {
public void properExceptionForExistingProxyDependencyMismatch() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AsyncConfig.class, AsyncBeanWithInterface.class, AsyncBeanUser.class);
try {
ctx.refresh();
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
assertTrue(ex.getCause() instanceof BeanNotOfRequiredTypeException);
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
ctx::refresh)
.withCauseInstanceOf(BeanNotOfRequiredTypeException.class);
ctx.close();
}
@@ -117,15 +111,9 @@ public class EnableAsyncTests {
public void properExceptionForResolvedProxyDependencyMismatch() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AsyncConfig.class, AsyncBeanUser.class, AsyncBeanWithInterface.class);
try {
ctx.refresh();
fail("Should have thrown UnsatisfiedDependencyException");
}
catch (UnsatisfiedDependencyException ex) {
assertTrue(ex.getCause() instanceof BeanNotOfRequiredTypeException);
}
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
ctx::refresh)
.withCauseInstanceOf(BeanNotOfRequiredTypeException.class);
ctx.close();
}
@@ -195,12 +183,13 @@ public class EnableAsyncTests {
/**
* Fails with classpath errors on trying to classload AnnotationAsyncExecutionAspect.
*/
@Test(expected = BeanDefinitionStoreException.class)
@Test
public void aspectModeAspectJAttemptsToRegisterAsyncAspect() {
@SuppressWarnings("resource")
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AspectJAsyncAnnotationConfig.class);
ctx.refresh();
assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(
ctx::refresh);
}
@Test
@@ -334,17 +323,9 @@ public class EnableAsyncTests {
@Test
@SuppressWarnings("resource")
public void exceptionThrownWithBeanNotOfRequiredTypeRootCause() {
try {
new AnnotationConfigApplicationContext(JdkProxyConfiguration.class);
fail("Should have thrown exception");
}
catch (Throwable ex) {
ex.printStackTrace();
while (ex.getCause() != null) {
ex = ex.getCause();
}
assertThat(ex, instanceOf(BeanNotOfRequiredTypeException.class));
}
assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
new AnnotationConfigApplicationContext(JdkProxyConfiguration.class))
.withCauseInstanceOf(BeanNotOfRequiredTypeException.class);
}

View File

@@ -58,6 +58,7 @@ import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
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.assertTrue;
@@ -306,16 +307,17 @@ public class ScheduledAnnotationBeanPostProcessorTests {
assertEquals(cal.getTime(), nextExecutionTime); // assert that 6:00 is next execution time
}
@Test(expected = BeanCreationException.class)
@Test
public void cronTaskWithInvalidZone() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(CronWithInvalidTimezoneTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("target", targetDefinition);
context.refresh();
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh);
}
@Test(expected = BeanCreationException.class)
@Test
public void cronTaskWithMethodValidation() {
BeanDefinition validationDefinition = new RootBeanDefinition(MethodValidationPostProcessor.class);
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
@@ -323,7 +325,8 @@ public class ScheduledAnnotationBeanPostProcessorTests {
context.registerBeanDefinition("methodValidation", validationDefinition);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("target", targetDefinition);
context.refresh();
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh);
}
@Test
@@ -661,31 +664,34 @@ public class ScheduledAnnotationBeanPostProcessorTests {
assertEquals("0 0 9-17 * * MON-FRI", task.getExpression());
}
@Test(expected = BeanCreationException.class)
@Test
public void emptyAnnotation() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(EmptyAnnotationTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("target", targetDefinition);
context.refresh();
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh);
}
@Test(expected = BeanCreationException.class)
@Test
public void invalidCron() throws Throwable {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(InvalidCronTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("target", targetDefinition);
context.refresh();
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh);
}
@Test(expected = BeanCreationException.class)
@Test
public void nonEmptyParamList() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(NonEmptyParamListTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("target", targetDefinition);
context.refresh();
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
context::refresh);
}

View File

@@ -33,6 +33,7 @@ import org.springframework.beans.factory.DisposableBean;
import org.springframework.core.task.AsyncListenableTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
@@ -90,28 +91,26 @@ public abstract class AbstractSchedulingTaskExecutorTests {
assertThreadNamePrefix(task);
}
@Test(expected = ExecutionException.class)
@Test
public void submitFailingRunnable() throws Exception {
TestTask task = new TestTask(0);
Future<?> future = executor.submit(task);
try {
future.get(1000, TimeUnit.MILLISECONDS);
}
catch (ExecutionException ex) {
assertTrue(future.isDone());
throw ex;
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(() ->
future.get(1000, TimeUnit.MILLISECONDS));
assertTrue(future.isDone());
}
@Test(expected = CancellationException.class)
@Test
public void submitRunnableWithGetAfterShutdown() throws Exception {
TestTask task1 = new TestTask(-1);
Future<?> future1 = executor.submit(task1);
TestTask task2 = new TestTask(-1);
Future<?> future2 = executor.submit(task2);
shutdownExecutor();
future1.get();
future2.get();
assertThatExceptionOfType(CancellationException.class).isThrownBy(() -> {
future1.get();
future2.get();
});
}
@Test
@@ -143,15 +142,17 @@ public abstract class AbstractSchedulingTaskExecutorTests {
assertSame(RuntimeException.class, outcome.getClass());
}
@Test(expected = CancellationException.class)
@Test
public void submitListenableRunnableWithGetAfterShutdown() throws Exception {
TestTask task1 = new TestTask(-1);
ListenableFuture<?> future1 = executor.submitListenable(task1);
TestTask task2 = new TestTask(-1);
ListenableFuture<?> future2 = executor.submitListenable(task2);
shutdownExecutor();
future1.get();
future2.get();
assertThatExceptionOfType(CancellationException.class).isThrownBy(() -> {
future1.get();
future2.get();
});
}
@Test
@@ -162,23 +163,26 @@ public abstract class AbstractSchedulingTaskExecutorTests {
assertEquals(THREAD_NAME_PREFIX, result.substring(0, THREAD_NAME_PREFIX.length()));
}
@Test(expected = ExecutionException.class)
@Test
public void submitFailingCallable() throws Exception {
TestCallable task = new TestCallable(0);
Future<String> future = executor.submit(task);
future.get(1000, TimeUnit.MILLISECONDS);
assertThatExceptionOfType(ExecutionException.class).isThrownBy(() ->
future.get(1000, TimeUnit.MILLISECONDS));
assertTrue(future.isDone());
}
@Test(expected = CancellationException.class)
@Test
public void submitCallableWithGetAfterShutdown() throws Exception {
TestCallable task1 = new TestCallable(-1);
Future<?> future1 = executor.submit(task1);
TestCallable task2 = new TestCallable(-1);
Future<?> future2 = executor.submit(task2);
shutdownExecutor();
future1.get(1000, TimeUnit.MILLISECONDS);
future2.get(1000, TimeUnit.MILLISECONDS);
assertThatExceptionOfType(CancellationException.class).isThrownBy(() -> {
future1.get(1000, TimeUnit.MILLISECONDS);
future2.get(1000, TimeUnit.MILLISECONDS);
});
}
@Test
@@ -210,7 +214,7 @@ public abstract class AbstractSchedulingTaskExecutorTests {
assertSame(RuntimeException.class, outcome.getClass());
}
@Test(expected = CancellationException.class)
@Test
public void submitListenableCallableWithGetAfterShutdown() throws Exception {
TestCallable task1 = new TestCallable(-1);
ListenableFuture<?> future1 = executor.submitListenable(task1);
@@ -218,7 +222,8 @@ public abstract class AbstractSchedulingTaskExecutorTests {
ListenableFuture<?> future2 = executor.submitListenable(task2);
shutdownExecutor();
future1.get(1000, TimeUnit.MILLISECONDS);
future2.get(1000, TimeUnit.MILLISECONDS);
assertThatExceptionOfType(CancellationException.class).isThrownBy(() ->
future2.get(1000, TimeUnit.MILLISECONDS));
}

View File

@@ -27,9 +27,9 @@ import org.springframework.core.task.NoOpRunnable;
import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup;
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;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock;
@@ -44,17 +44,9 @@ public class ScheduledExecutorFactoryBeanTests {
@Test
public void testThrowsExceptionIfPoolSizeIsLessThanZero() throws Exception {
try {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
factory.setPoolSize(-1);
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
new NoOpScheduledExecutorTask()
});
factory.afterPropertiesSet();
fail("Pool size less than zero");
}
catch (IllegalArgumentException expected) {
}
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
assertThatIllegalArgumentException().isThrownBy(() ->
factory.setPoolSize(-1));
}
@Test

View File

@@ -31,6 +31,7 @@ import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.util.ErrorHandler;
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;
@@ -98,17 +99,13 @@ public class ThreadPoolTaskSchedulerTests extends AbstractSchedulingTaskExecutor
assertThreadNamePrefix(task);
}
@Test(expected = ExecutionException.class)
@Test
public void scheduleOneTimeFailingTaskWithoutErrorHandler() throws Exception {
TestTask task = new TestTask(0);
Future<?> future = scheduler.schedule(task, new Date());
try {
future.get(1000, TimeUnit.MILLISECONDS);
}
catch (ExecutionException ex) {
assertTrue(future.isDone());
throw ex;
}
assertThatExceptionOfType(ExecutionException.class).isThrownBy(() ->
future.get(1000, TimeUnit.MILLISECONDS));
assertTrue(future.isDone());
}
@Test

View File

@@ -31,6 +31,7 @@ import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.CustomizableThreadCreator;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -76,9 +77,10 @@ public class ExecutorBeanDefinitionParserTests {
assertEquals(42, getMaxPoolSize(executor));
}
@Test(expected = BeanCreationException.class)
@Test
public void invalidPoolSize() {
this.context.getBean("invalidPoolSize");
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
this.context.getBean("invalidPoolSize"));
}
@Test
@@ -126,9 +128,10 @@ public class ExecutorBeanDefinitionParserTests {
assertEquals(true, getAllowCoreThreadTimeOut(executor));
}
@Test(expected = BeanCreationException.class)
@Test
public void propertyPlaceholderWithInvalidPoolSize() {
this.context.getBean("propertyPlaceholderWithInvalidPoolSize");
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() ->
this.context.getBean("propertyPlaceholderWithInvalidPoolSize"));
}
@Test

View File

@@ -20,6 +20,7 @@ import java.util.Date;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -49,24 +50,28 @@ public class CronSequenceGeneratorTests {
new CronSequenceGenerator("0 */2 1-4 * * *").next(new Date(2012, 6, 1, 9, 0)));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void with0Increment() {
new CronSequenceGenerator("*/0 * * * * *").next(new Date(2012, 6, 1, 9, 0));
assertThatIllegalArgumentException().isThrownBy(() ->
new CronSequenceGenerator("*/0 * * * * *").next(new Date(2012, 6, 1, 9, 0)));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void withNegativeIncrement() {
new CronSequenceGenerator("*/-1 * * * * *").next(new Date(2012, 6, 1, 9, 0));
assertThatIllegalArgumentException().isThrownBy(() ->
new CronSequenceGenerator("*/-1 * * * * *").next(new Date(2012, 6, 1, 9, 0)));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void withInvertedMinuteRange() {
new CronSequenceGenerator("* 6-5 * * * *").next(new Date(2012, 6, 1, 9, 0));
assertThatIllegalArgumentException().isThrownBy(() ->
new CronSequenceGenerator("* 6-5 * * * *").next(new Date(2012, 6, 1, 9, 0)));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void withInvertedHourRange() {
new CronSequenceGenerator("* * 6-5 * * *").next(new Date(2012, 6, 1, 9, 0));
assertThatIllegalArgumentException().isThrownBy(() ->
new CronSequenceGenerator("* * 6-5 * * *").next(new Date(2012, 6, 1, 9, 0)));
}
@Test

View File

@@ -31,6 +31,7 @@ import org.junit.runners.Parameterized.Parameters;
import org.springframework.scheduling.TriggerContext;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
/**
@@ -488,7 +489,7 @@ public class CronTriggerTests {
assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context2));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testNonExistentSpecificDate() throws Exception {
// TODO: maybe try and detect this as a special case in parser?
CronTrigger trigger = new CronTrigger("0 0 0 31 6 *", timeZone);
@@ -496,7 +497,8 @@ public class CronTriggerTests {
calendar.set(Calendar.MONTH, 2);
Date date = calendar.getTime();
TriggerContext context1 = getTriggerContext(date);
trigger.nextExecutionTime(context1);
assertThatIllegalArgumentException().isThrownBy(() ->
trigger.nextExecutionTime(context1));
// new CronTrigger("0 0 0 30 1 ?", timeZone);
}
@@ -605,64 +607,76 @@ public class CronTriggerTests {
assertEquals(trigger1, trigger2);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSecondInvalid() throws Exception {
new CronTrigger("77 * * * * *", timeZone);
assertThatIllegalArgumentException().isThrownBy(() ->
new CronTrigger("77 * * * * *", timeZone));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testSecondRangeInvalid() throws Exception {
new CronTrigger("44-77 * * * * *", timeZone);
assertThatIllegalArgumentException().isThrownBy(() ->
new CronTrigger("44-77 * * * * *", timeZone));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testMinuteInvalid() throws Exception {
new CronTrigger("* 77 * * * *", timeZone);
assertThatIllegalArgumentException().isThrownBy(() ->
new CronTrigger("* 77 * * * *", timeZone));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testMinuteRangeInvalid() throws Exception {
new CronTrigger("* 44-77 * * * *", timeZone);
assertThatIllegalArgumentException().isThrownBy(() ->
new CronTrigger("* 44-77 * * * *", timeZone));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testHourInvalid() throws Exception {
new CronTrigger("* * 27 * * *", timeZone);
assertThatIllegalArgumentException().isThrownBy(() ->
new CronTrigger("* * 27 * * *", timeZone));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testHourRangeInvalid() throws Exception {
new CronTrigger("* * 23-28 * * *", timeZone);
assertThatIllegalArgumentException().isThrownBy(() ->
new CronTrigger("* * 23-28 * * *", timeZone));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testDayInvalid() throws Exception {
new CronTrigger("* * * 45 * *", timeZone);
assertThatIllegalArgumentException().isThrownBy(() ->
new CronTrigger("* * * 45 * *", timeZone));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testDayRangeInvalid() throws Exception {
new CronTrigger("* * * 28-45 * *", timeZone);
assertThatIllegalArgumentException().isThrownBy(() ->
new CronTrigger("* * * 28-45 * *", timeZone));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testMonthInvalid() throws Exception {
new CronTrigger("0 0 0 25 13 ?", timeZone);
assertThatIllegalArgumentException().isThrownBy(() ->
new CronTrigger("0 0 0 25 13 ?", timeZone));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testMonthInvalidTooSmall() throws Exception {
new CronTrigger("0 0 0 25 0 ?", timeZone);
assertThatIllegalArgumentException().isThrownBy(() ->
new CronTrigger("0 0 0 25 0 ?", timeZone));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testDayOfMonthInvalid() throws Exception {
new CronTrigger("0 0 0 32 12 ?", timeZone);
assertThatIllegalArgumentException().isThrownBy(() ->
new CronTrigger("0 0 0 32 12 ?", timeZone));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testMonthRangeInvalid() throws Exception {
new CronTrigger("* * * * 11-13 *", timeZone);
assertThatIllegalArgumentException().isThrownBy(() ->
new CronTrigger("* * * * 11-13 *", timeZone));
}
@Test

View File

@@ -37,6 +37,8 @@ import org.springframework.scripting.TestBeanAwareMessenger;
import org.springframework.scripting.support.ScriptFactoryPostProcessor;
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.assertFalse;
import static org.junit.Assert.assertNotNull;
@@ -44,7 +46,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.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -199,13 +200,9 @@ public class BshScriptFactoryTests {
@Test
public void scriptCompilationException() {
try {
new ClassPathXmlApplicationContext("org/springframework/scripting/bsh/bshBrokenContext.xml");
fail("Must throw exception for broken script file");
}
catch (NestedRuntimeException ex) {
assertTrue(ex.contains(ScriptCompilationException.class));
}
assertThatExceptionOfType(NestedRuntimeException.class).isThrownBy(() ->
new ClassPathXmlApplicationContext("org/springframework/scripting/bsh/bshBrokenContext.xml"))
.matches(ex -> ex.contains(ScriptCompilationException.class));
}
@Test
@@ -216,43 +213,28 @@ public class BshScriptFactoryTests {
given(script.isModified()).willReturn(true);
BshScriptFactory factory = new BshScriptFactory(
ScriptFactoryPostProcessor.INLINE_SCRIPT_PREFIX + badScript, Messenger.class);
try {
assertThatExceptionOfType(BshScriptUtils.BshExecutionException.class).isThrownBy(() -> {
Messenger messenger = (Messenger) factory.getScriptedObject(script, Messenger.class);
messenger.getMessage();
fail("Must have thrown a BshScriptUtils.BshExecutionException.");
}
catch (BshScriptUtils.BshExecutionException expected) {
}
});
}
@Test
public void ctorWithNullScriptSourceLocator() {
try {
new BshScriptFactory(null, Messenger.class);
fail("Must have thrown exception by this point.");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
new BshScriptFactory(null, Messenger.class));
}
@Test
public void ctorWithEmptyScriptSourceLocator() {
try {
new BshScriptFactory("", Messenger.class);
fail("Must have thrown exception by this point.");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
new BshScriptFactory("", Messenger.class));
}
@Test
public void ctorWithWhitespacedScriptSourceLocator() {
try {
new BshScriptFactory("\n ", Messenger.class);
fail("Must have thrown exception by this point.");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
new BshScriptFactory("\n ", Messenger.class));
}
@Test

View File

@@ -21,8 +21,8 @@ import org.junit.Test;
import org.springframework.context.support.GenericXmlApplicationContext;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author Dave Syer
@@ -38,15 +38,10 @@ public class GroovyAspectIntegrationTests {
LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class);
assertEquals(0, logAdvice.getCountThrows());
try {
bean.sayHello();
fail("Expected exception");
}
catch (RuntimeException ex) {
assertEquals("TestServiceImpl", ex.getMessage());
}
assertThatExceptionOfType(RuntimeException.class).isThrownBy(
bean::sayHello)
.withMessage("TestServiceImpl");
assertEquals(1, logAdvice.getCountThrows());
}
@Test
@@ -56,13 +51,9 @@ public class GroovyAspectIntegrationTests {
LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class);
assertEquals(0, logAdvice.getCountThrows());
try {
bean.sayHello();
fail("Expected exception");
}
catch (RuntimeException ex) {
assertEquals("GroovyServiceImpl", ex.getMessage());
}
assertThatExceptionOfType(RuntimeException.class).isThrownBy(
bean::sayHello)
.withMessage("GroovyServiceImpl");
assertEquals(1, logAdvice.getCountThrows());
}
@@ -74,13 +65,9 @@ public class GroovyAspectIntegrationTests {
LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class);
assertEquals(0, logAdvice.getCountThrows());
try {
bean.sayHello();
fail("Expected exception");
}
catch (RuntimeException ex) {
assertEquals("GroovyServiceImpl", ex.getMessage());
}
assertThatExceptionOfType(RuntimeException.class).isThrownBy(
bean::sayHello)
.withMessage("GroovyServiceImpl");
// No proxy here because the pointcut only applies to the concrete class, not the interface
assertEquals(0, logAdvice.getCountThrows());
assertEquals(0, logAdvice.getCountBefore());
@@ -93,13 +80,9 @@ public class GroovyAspectIntegrationTests {
LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class);
assertEquals(0, logAdvice.getCountThrows());
try {
bean.sayHello();
fail("Expected exception");
}
catch (TestException ex) {
assertEquals("GroovyServiceImpl", ex.getMessage());
}
assertThatExceptionOfType(RuntimeException.class).isThrownBy(
bean::sayHello)
.withMessage("GroovyServiceImpl");
assertEquals(1, logAdvice.getCountBefore());
assertEquals(1, logAdvice.getCountThrows());
}

View File

@@ -26,8 +26,8 @@ import org.springframework.core.io.ClassPathResource;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author Dave Syer
@@ -95,13 +95,9 @@ public class GroovyAspectTests {
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)
.withMessage(message);
assertEquals(1, logAdvice.getCountThrows());
}

View File

@@ -45,13 +45,16 @@ import org.springframework.stereotype.Component;
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.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.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;
@@ -262,13 +265,9 @@ public class GroovyScriptFactoryTests {
@Test
public void testScriptCompilationException() throws Exception {
try {
new ClassPathXmlApplicationContext("org/springframework/scripting/groovy/groovyBrokenContext.xml");
fail("Should throw exception for broken script file");
}
catch (NestedRuntimeException ex) {
assertTrue("Wrong root cause: " + ex, ex.contains(ScriptCompilationException.class));
}
assertThatExceptionOfType(NestedRuntimeException.class).isThrownBy(() ->
new ClassPathXmlApplicationContext("org/springframework/scripting/groovy/groovyBrokenContext.xml"))
.matches(ex -> ex.contains(ScriptCompilationException.class));
}
@Test
@@ -279,13 +278,9 @@ public class GroovyScriptFactoryTests {
given(script.suggestedClassName()).willReturn("someName");
GroovyScriptFactory factory = new GroovyScriptFactory(ScriptFactoryPostProcessor.INLINE_SCRIPT_PREFIX
+ badScript);
try {
factory.getScriptedObject(script);
fail("Must have thrown a ScriptCompilationException (no public no-arg ctor in scripted class).");
}
catch (ScriptCompilationException expected) {
assertTrue(expected.contains(NoSuchMethodException.class));
}
assertThatExceptionOfType(ScriptCompilationException.class).isThrownBy(() ->
factory.getScriptedObject(script))
.matches(ex -> ex.contains(NoSuchMethodException.class));
}
@Test
@@ -312,55 +307,35 @@ public class GroovyScriptFactoryTests {
@Test
public void testWithTwoClassesDefinedInTheOneGroovyFile_WrongClassFirst() throws Exception {
try {
ApplicationContext ctx = new ClassPathXmlApplicationContext("twoClassesWrongOneFirst.xml", getClass());
ctx.getBean("messenger", Messenger.class);
fail("Must have failed: two classes defined in GroovyScriptFactory source, non-Messenger class defined first.");
}
// just testing for failure here, hence catching Exception...
catch (Exception expected) {
}
assertThatExceptionOfType(Exception.class).as("two classes defined in GroovyScriptFactory source, non-Messenger class defined first").isThrownBy(() -> {
ApplicationContext ctx = new ClassPathXmlApplicationContext("twoClassesWrongOneFirst.xml", getClass());
ctx.getBean("messenger", Messenger.class);
});
}
@Test
public void testCtorWithNullScriptSourceLocator() throws Exception {
try {
new GroovyScriptFactory(null);
fail("Must have thrown exception by this point.");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
new GroovyScriptFactory(null));
}
@Test
public void testCtorWithEmptyScriptSourceLocator() throws Exception {
try {
new GroovyScriptFactory("");
fail("Must have thrown exception by this point.");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
new GroovyScriptFactory(""));
}
@Test
public void testCtorWithWhitespacedScriptSourceLocator() throws Exception {
try {
new GroovyScriptFactory("\n ");
fail("Must have thrown exception by this point.");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() ->
new GroovyScriptFactory("\n "));
}
@Test
public void testWithInlineScriptWithLeadingWhitespace() throws Exception {
try {
new ClassPathXmlApplicationContext("lwspBadGroovyContext.xml", getClass());
fail("Must have thrown a BeanCreationException ('inline:' prefix was preceded by whitespace");
}
catch (BeanCreationException expected) {
assertTrue(expected.contains(FileNotFoundException.class));
}
assertThatExceptionOfType(BeanCreationException.class).as("'inline:' prefix was preceded by whitespace").isThrownBy(() ->
new ClassPathXmlApplicationContext("lwspBadGroovyContext.xml", getClass()))
.matches(ex -> ex.contains(FileNotFoundException.class));
}
@Test
@@ -377,12 +352,8 @@ public class GroovyScriptFactoryTests {
@Test
public void testGetScriptedObjectDoesChokeOnNullScriptSourceBeingPassedIn() throws Exception {
GroovyScriptFactory factory = new GroovyScriptFactory("a script source locator (doesn't matter here)");
try {
factory.getScriptedObject(null);
fail("Must have thrown a NullPointerException as per contract ('null' ScriptSource supplied");
}
catch (NullPointerException expected) {
}
assertThatNullPointerException().as("NullPointerException as per contract ('null' ScriptSource supplied)").isThrownBy(() ->
factory.getScriptedObject(null));
}
@Test
@@ -556,15 +527,11 @@ public class GroovyScriptFactoryTests {
private void testMetaClass(String xmlFile) {
// expect the exception we threw in the custom metaclass to show it got invoked
try {
ApplicationContext ctx = new ClassPathXmlApplicationContext(xmlFile);
Calculator calc = (Calculator) ctx.getBean("delegatingCalculator");
calc.add(1, 2);
fail("expected IllegalStateException");
}
catch (IllegalStateException ex) {
assertEquals("Gotcha", ex.getMessage());
}
ApplicationContext ctx = new ClassPathXmlApplicationContext(xmlFile);
Calculator calc = (Calculator) ctx.getBean("delegatingCalculator");
assertThatIllegalStateException().isThrownBy(() ->
calc.add(1, 2))
.withMessage("Gotcha");
}
@Test

View File

@@ -20,6 +20,7 @@ import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@@ -27,9 +28,10 @@ import static org.mockito.Mockito.mock;
*/
public class RefreshableScriptTargetSourceTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void createWithNullScriptSource() throws Exception {
new RefreshableScriptTargetSource(mock(BeanFactory.class), "a.bean", null, null, false);
assertThatIllegalArgumentException().isThrownBy(() ->
new RefreshableScriptTargetSource(mock(BeanFactory.class), "a.bean", null, null, false));
}
}

View File

@@ -31,11 +31,11 @@ import org.springframework.scripting.groovy.GroovyScriptFactory;
import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup;
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.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
/**
@@ -91,12 +91,8 @@ public class ScriptFactoryPostProcessorTests {
@Test
public void testThrowsExceptionIfGivenNonAbstractBeanFactoryImplementation() throws Exception {
try {
new ScriptFactoryPostProcessor().setBeanFactory(mock(BeanFactory.class));
fail("Must have thrown exception by this point.");
}
catch (IllegalStateException expected) {
}
assertThatIllegalStateException().isThrownBy(() ->
new ScriptFactoryPostProcessor().setBeanFactory(mock(BeanFactory.class)));
}
@Test
@@ -213,13 +209,9 @@ public class ScriptFactoryPostProcessorTests {
// needs The Sundays compiler; must NOT throw any exception here...
source.setScript("I keep hoping you are the same as me, and I'll send you letters and come to your house for tea");
Messenger refreshedMessenger = (Messenger) ctx.getBean(MESSENGER_BEAN_NAME);
try {
refreshedMessenger.getMessage();
fail("Must have thrown an Exception (invalid script)");
}
catch (FatalBeanException expected) {
assertTrue(expected.contains(ScriptCompilationException.class));
}
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() ->
refreshedMessenger.getMessage())
.matches(ex -> ex.contains(ScriptCompilationException.class));
}
@Test

View File

@@ -18,6 +18,7 @@ package org.springframework.scripting.support;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -35,19 +36,22 @@ public class StaticScriptSourceTests {
private final StaticScriptSource source = new StaticScriptSource(SCRIPT_TEXT);
@Test(expected = IllegalArgumentException.class)
@Test
public void createWithNullScript() throws Exception {
new StaticScriptSource(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new StaticScriptSource(null));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void createWithEmptyScript() throws Exception {
new StaticScriptSource("");
assertThatIllegalArgumentException().isThrownBy(() ->
new StaticScriptSource(""));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void createWithWhitespaceOnlyScript() throws Exception {
new StaticScriptSource(" \n\n\t \t\n");
assertThatIllegalArgumentException().isThrownBy(() ->
new StaticScriptSource(" \n\n\t \t\n"));
}
@Test

View File

@@ -34,6 +34,7 @@ import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
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;
@@ -100,10 +101,11 @@ public class ModelMapTests {
assertEquals("bing", string);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testOneArgCtorWithNull() {
//Null model arguments added without a name being explicitly supplied are not allowed
new ModelMap(null);
assertThatIllegalArgumentException().isThrownBy(() ->
new ModelMap(null));
}
@Test
@@ -124,11 +126,12 @@ public class ModelMapTests {
assertEquals(0, model.size());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testAddObjectWithNull() throws Exception {
// Null model arguments added without a name being explicitly supplied are not allowed
ModelMap model = new ModelMap();
model.addAttribute(null);
assertThatIllegalArgumentException().isThrownBy(() ->
model.addAttribute(null));
}
@Test
@@ -154,14 +157,15 @@ public class ModelMapTests {
assertEquals(0, model.size());
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testAddAllObjectsWithSparseArrayList() throws Exception {
// Null model arguments added without a name being explicitly supplied are not allowed
ModelMap model = new ModelMap();
ArrayList<String> list = new ArrayList<>();
list.add("bing");
list.add(null);
model.addAllAttributes(list);
assertThatIllegalArgumentException().isThrownBy(() ->
model.addAllAttributes(list));
}
@Test

View File

@@ -28,11 +28,10 @@ import org.springframework.beans.PropertyValue;
import org.springframework.tests.sample.beans.FieldAccessBean;
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.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@@ -74,14 +73,8 @@ public class DataBinderFieldAccessTests {
pvs.addPropertyValue(new PropertyValue("name", "Rod"));
pvs.addPropertyValue(new PropertyValue("age", new Integer(32)));
pvs.addPropertyValue(new PropertyValue("nonExisting", "someValue"));
try {
binder.bind(pvs);
fail("Should have thrown NotWritablePropertyException");
}
catch (NotWritablePropertyException ex) {
// expected
}
assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() ->
binder.bind(pvs));
}
@Test
@@ -93,31 +86,24 @@ public class DataBinderFieldAccessTests {
pvs.addPropertyValue(new PropertyValue("name", "Rod"));
pvs.addPropertyValue(new PropertyValue("age", "32x"));
binder.bind(pvs);
assertThatExceptionOfType(BindException.class).isThrownBy(
binder::close)
.satisfies(ex -> {
assertThat(rod.getName()).isEqualTo("Rod");
Map<?, ?> map = binder.getBindingResult().getModel();
FieldAccessBean tb = (FieldAccessBean) map.get("person");
assertThat(tb).isEqualTo(rod);
try {
binder.close();
fail("Should have thrown BindException");
}
catch (BindException ex) {
assertTrue("changed name correctly", rod.getName().equals("Rod"));
//assertTrue("changed age correctly", rod.getAge() == 32);
Map<?, ?> map = binder.getBindingResult().getModel();
//assertTrue("There are 3 element in map", m.size() == 1);
FieldAccessBean tb = (FieldAccessBean) map.get("person");
assertTrue("Same object", tb.equals(rod));
BindingResult br = (BindingResult) map.get(BindingResult.MODEL_KEY_PREFIX + "person");
assertTrue("Added itself to map", br == binder.getBindingResult());
assertTrue(br.hasErrors());
assertTrue("Correct number of errors", br.getErrorCount() == 1);
assertTrue("Has age errors", br.hasFieldErrors("age"));
assertTrue("Correct number of age errors", br.getFieldErrorCount("age") == 1);
assertEquals("32x", binder.getBindingResult().getFieldValue("age"));
assertEquals("32x", binder.getBindingResult().getFieldError("age").getRejectedValue());
assertEquals(0, tb.getAge());
}
BindingResult br = (BindingResult) map.get(BindingResult.MODEL_KEY_PREFIX + "person");
assertThat(br).isSameAs(binder.getBindingResult());
assertThat(br.hasErrors()).isTrue();
assertThat(br.getErrorCount()).isEqualTo(1);
assertThat(br.hasFieldErrors()).isTrue();
assertThat(br.getFieldErrorCount("age")).isEqualTo(1);
assertThat(binder.getBindingResult().getFieldValue("age")).isEqualTo("32x");
assertThat(binder.getBindingResult().getFieldError("age").getRejectedValue()).isEqualTo("32x");
assertThat(tb.getAge()).isEqualTo(0);
});
}
@Test
@@ -171,34 +157,25 @@ public class DataBinderFieldAccessTests {
pvs.addPropertyValue(new PropertyValue("spouse", "Kerry"));
binder.bind(pvs);
try {
binder.close();
fail("Should have thrown BindException");
}
catch (BindException ex) {
assertTrue("changed name correctly", rod.getName().equals("Rod"));
//assertTrue("changed age correctly", rod.getAge() == 32);
Map<?, ?> model = binder.getBindingResult().getModel();
//assertTrue("There are 3 element in map", m.size() == 1);
FieldAccessBean tb = (FieldAccessBean) model.get("person");
assertTrue("Same object", tb.equals(rod));
BindingResult br = (BindingResult) model.get(BindingResult.MODEL_KEY_PREFIX + "person");
assertTrue("Added itself to map", br == binder.getBindingResult());
assertTrue(br.hasErrors());
assertTrue("Correct number of errors", br.getErrorCount() == 1);
assertTrue("Has age errors", br.hasFieldErrors("age"));
assertTrue("Correct number of age errors", br.getFieldErrorCount("age") == 1);
assertEquals("32x", binder.getBindingResult().getFieldValue("age"));
assertEquals("32x", binder.getBindingResult().getFieldError("age").getRejectedValue());
assertEquals(0, tb.getAge());
assertTrue("Does not have spouse errors", !br.hasFieldErrors("spouse"));
assertEquals("Kerry", binder.getBindingResult().getFieldValue("spouse"));
assertNotNull(tb.getSpouse());
}
assertThatExceptionOfType(BindException.class).isThrownBy(
binder::close)
.satisfies(ex -> {
assertThat(rod.getName()).isEqualTo("Rod");
Map<?, ?> model = binder.getBindingResult().getModel();
FieldAccessBean tb = (FieldAccessBean) model.get("person");
assertThat(tb).isEqualTo(rod);
BindingResult br = (BindingResult) model.get(BindingResult.MODEL_KEY_PREFIX + "person");
assertThat(br).isSameAs(binder.getBindingResult());
assertThat(br.hasErrors()).isTrue();
assertThat(br.getErrorCount()).isEqualTo(1);
assertThat(br.hasFieldErrors("age")).isTrue();
assertThat(br.getFieldErrorCount("age")).isEqualTo(1);
assertThat(binder.getBindingResult().getFieldValue("age")).isEqualTo("32x");
assertThat(binder.getBindingResult().getFieldError("age").getRejectedValue()).isEqualTo("32x");
assertThat(tb.getAge()).isEqualTo(0);
assertThat(br.hasFieldErrors("spouse")).isFalse();
assertThat(binder.getBindingResult().getFieldValue("spouse")).isEqualTo("Kerry");
assertThat(tb.getSpouse()).isNotNull();
});
}
}

View File

@@ -67,14 +67,14 @@ import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.ObjectUtils;
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.assertThatIllegalStateException;
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.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Rod Johnson
@@ -159,14 +159,8 @@ public class DataBinderTests {
pvs.add("name", "Rod");
pvs.add("age", 32);
pvs.add("nonExisting", "someValue");
try {
binder.bind(pvs);
fail("Should have thrown NotWritablePropertyException");
}
catch (NotWritablePropertyException ex) {
// expected
}
assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() ->
binder.bind(pvs));
}
@Test
@@ -176,14 +170,8 @@ public class DataBinderTests {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("name", "Rod");
pvs.add("spouse.age", 32);
try {
binder.bind(pvs);
fail("Should have thrown NullValueInNestedPathException");
}
catch (NullValueInNestedPathException ex) {
// expected
}
assertThatExceptionOfType(NullValueInNestedPathException.class).isThrownBy(() ->
binder.bind(pvs));
}
@Test
@@ -207,68 +195,57 @@ public class DataBinderTests {
pvs.add("age", "32x");
pvs.add("touchy", "m.y");
binder.bind(pvs);
assertThatExceptionOfType(BindException.class).isThrownBy(
binder::close)
.satisfies(ex -> {
assertThat(rod.getName()).isEqualTo("Rod");
Map<?, ?> map = binder.getBindingResult().getModel();
TestBean tb = (TestBean) map.get("person");
assertThat(tb).isSameAs(rod);
try {
binder.close();
fail("Should have thrown BindException");
}
catch (BindException ex) {
assertTrue("changed name correctly", rod.getName().equals("Rod"));
//assertTrue("changed age correctly", rod.getAge() == 32);
BindingResult br = (BindingResult) map.get(BindingResult.MODEL_KEY_PREFIX + "person");
assertThat(BindingResultUtils.getBindingResult(map, "person")).isEqualTo(br);
assertThat(BindingResultUtils.getRequiredBindingResult(map, "person")).isEqualTo(br);
Map<?, ?> map = binder.getBindingResult().getModel();
//assertTrue("There are 3 element in map", m.size() == 1);
TestBean tb = (TestBean) map.get("person");
assertTrue("Same object", tb.equals(rod));
assertThat(BindingResultUtils.getBindingResult(map, "someOtherName")).isNull();
assertThatIllegalStateException().isThrownBy(() ->
BindingResultUtils.getRequiredBindingResult(map, "someOtherName"));
BindingResult br = (BindingResult) map.get(BindingResult.MODEL_KEY_PREFIX + "person");
assertSame(br, BindingResultUtils.getBindingResult(map, "person"));
assertSame(br, BindingResultUtils.getRequiredBindingResult(map, "person"));
assertThat(binder.getBindingResult()).as("Added itself to map").isSameAs(br);
assertThat(br.hasErrors()).isTrue();
assertThat(br.getErrorCount()).isEqualTo(2);
assertNull(BindingResultUtils.getBindingResult(map, "someOtherName"));
try {
BindingResultUtils.getRequiredBindingResult(map, "someOtherName");
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException expected) {
}
assertThat(br.hasFieldErrors("age")).isTrue();
assertThat(br.getFieldErrorCount("age")).isEqualTo(1);
assertThat(binder.getBindingResult().getFieldValue("age")).isEqualTo("32x");
FieldError ageError = binder.getBindingResult().getFieldError("age");
assertThat(ageError).isNotNull();
assertThat(ageError.getCode()).isEqualTo("typeMismatch");
assertThat(ageError.getRejectedValue()).isEqualTo("32x");
assertThat(ageError.contains(TypeMismatchException.class)).isTrue();
assertThat(ageError.contains(NumberFormatException.class)).isTrue();
assertThat(ageError.unwrap(NumberFormatException.class).getMessage()).contains("32x");
assertThat(tb.getAge()).isEqualTo(0);
assertTrue("Added itself to map", br == binder.getBindingResult());
assertTrue(br.hasErrors());
assertTrue("Correct number of errors", br.getErrorCount() == 2);
assertThat(br.hasFieldErrors("touchy")).isTrue();
assertThat(br.getFieldErrorCount("touchy")).isEqualTo(1);
assertThat(binder.getBindingResult().getFieldValue("touchy")).isEqualTo("m.y");
FieldError touchyError = binder.getBindingResult().getFieldError("touchy");
assertThat(touchyError).isNotNull();
assertThat(touchyError.getCode()).isEqualTo("methodInvocation");
assertThat(touchyError.getRejectedValue()).isEqualTo("m.y");
assertThat(touchyError.contains(MethodInvocationException.class)).isTrue();
assertThat(touchyError.unwrap(MethodInvocationException.class).getCause().getMessage()).contains("a .");
assertThat(tb.getTouchy()).isNull();
assertTrue("Has age errors", br.hasFieldErrors("age"));
assertTrue("Correct number of age errors", br.getFieldErrorCount("age") == 1);
assertEquals("32x", binder.getBindingResult().getFieldValue("age"));
FieldError ageError = binder.getBindingResult().getFieldError("age");
assertNotNull(ageError);
assertEquals("typeMismatch", ageError.getCode());
assertEquals("32x", ageError.getRejectedValue());
assertTrue(ageError.contains(TypeMismatchException.class));
assertTrue(ageError.contains(NumberFormatException.class));
assertTrue(ageError.unwrap(NumberFormatException.class).getMessage().contains("32x"));
assertEquals(0, tb.getAge());
assertTrue("Has touchy errors", br.hasFieldErrors("touchy"));
assertTrue("Correct number of touchy errors", br.getFieldErrorCount("touchy") == 1);
assertEquals("m.y", binder.getBindingResult().getFieldValue("touchy"));
FieldError touchyError = binder.getBindingResult().getFieldError("touchy");
assertNotNull(touchyError);
assertEquals("methodInvocation", touchyError.getCode());
assertEquals("m.y", touchyError.getRejectedValue());
assertTrue(touchyError.contains(MethodInvocationException.class));
assertTrue(touchyError.unwrap(MethodInvocationException.class).getCause().getMessage().contains("a ."));
assertNull(tb.getTouchy());
rod = new TestBean();
binder = new DataBinder(rod, "person");
pvs = new MutablePropertyValues();
pvs.add("name", "Rod");
pvs.add("age", "32x");
pvs.add("touchy", "m.y");
binder.bind(pvs);
assertEquals(binder.getBindingResult(), ex.getBindingResult());
}
DataBinder binder2 = new DataBinder(new TestBean(), "person");
MutablePropertyValues pvs2 = new MutablePropertyValues();
pvs2.add("name", "Rod");
pvs2.add("age", "32x");
pvs2.add("touchy", "m.y");
binder2.bind(pvs2);
assertEquals(binder2.getBindingResult(), ex.getBindingResult());
});
}
@Test
@@ -278,14 +255,9 @@ public class DataBinderTests {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("class.classLoader.URLs[0]", "https://myserver");
binder.setIgnoreUnknownFields(false);
try {
binder.bind(pvs);
fail("Should have thrown NotWritablePropertyException");
}
catch (NotWritablePropertyException ex) {
assertTrue(ex.getMessage().contains("classLoader"));
}
assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() ->
binder.bind(pvs))
.withMessageContaining("classLoader");
}
@Test
@@ -319,46 +291,41 @@ public class DataBinderTests {
pvs.add("spouse", "Kerry");
binder.bind(pvs);
try {
binder.close();
fail("Should have thrown BindException");
}
catch (BindException ex) {
assertTrue("changed name correctly", rod.getName().equals("Rod"));
//assertTrue("changed age correctly", rod.getAge() == 32);
assertThatExceptionOfType(BindException.class).isThrownBy(
binder::close)
.satisfies(ex -> {
assertThat(rod.getName()).isEqualTo("Rod");
Map<?, ?> model = binder.getBindingResult().getModel();
TestBean tb = (TestBean) model.get("person");
assertThat(tb).isEqualTo(rod);
Map<?, ?> model = binder.getBindingResult().getModel();
//assertTrue("There are 3 element in map", m.size() == 1);
TestBean tb = (TestBean) model.get("person");
assertTrue("Same object", tb.equals(rod));
BindingResult br = (BindingResult) model.get(BindingResult.MODEL_KEY_PREFIX + "person");
assertThat(binder.getBindingResult()).isSameAs(br);
assertThat(br.hasErrors()).isTrue();
assertThat(br.getErrorCount()).isEqualTo(2);
BindingResult br = (BindingResult) model.get(BindingResult.MODEL_KEY_PREFIX + "person");
assertTrue("Added itself to map", br == binder.getBindingResult());
assertTrue(br.hasErrors());
assertTrue("Correct number of errors", br.getErrorCount() == 2);
assertThat(br.hasFieldErrors("age")).isTrue();
assertThat(br.getFieldErrorCount("age")).isEqualTo(1);
assertThat(binder.getBindingResult().getFieldValue("age")).isEqualTo("32x");
FieldError ageError = binder.getBindingResult().getFieldError("age");
assertThat(ageError).isNotNull();
assertThat(ageError.getCode()).isEqualTo("typeMismatch");
assertThat(ageError.getRejectedValue()).isEqualTo("32x");
assertThat(tb.getAge()).isEqualTo(0);
assertTrue("Has age errors", br.hasFieldErrors("age"));
assertTrue("Correct number of age errors", br.getFieldErrorCount("age") == 1);
assertEquals("32x", binder.getBindingResult().getFieldValue("age"));
FieldError ageError = binder.getBindingResult().getFieldError("age");
assertNotNull(ageError);
assertEquals("typeMismatch", ageError.getCode());
assertEquals("32x", ageError.getRejectedValue());
assertEquals(0, tb.getAge());
assertThat(br.hasFieldErrors("touchy")).isTrue();
assertThat(br.getFieldErrorCount("touchy")).isEqualTo(1);
assertThat(binder.getBindingResult().getFieldValue("touchy")).isEqualTo("m.y");
FieldError touchyError = binder.getBindingResult().getFieldError("touchy");
assertThat(touchyError).isNotNull();
assertThat(touchyError.getCode()).isEqualTo("methodInvocation");
assertThat(touchyError.getRejectedValue()).isEqualTo("m.y");
assertThat(tb.getTouchy()).isNull();
assertTrue("Has touchy errors", br.hasFieldErrors("touchy"));
assertTrue("Correct number of touchy errors", br.getFieldErrorCount("touchy") == 1);
assertEquals("m.y", binder.getBindingResult().getFieldValue("touchy"));
FieldError touchyError = binder.getBindingResult().getFieldError("touchy");
assertNotNull(touchyError);
assertEquals("methodInvocation", touchyError.getCode());
assertEquals("m.y", touchyError.getRejectedValue());
assertNull(tb.getTouchy());
assertTrue("Does not have spouse errors", !br.hasFieldErrors("spouse"));
assertEquals("Kerry", binder.getBindingResult().getFieldValue("spouse"));
assertNotNull(tb.getSpouse());
}
assertThat(br.hasFieldErrors("spouse")).isFalse();
assertThat(binder.getBindingResult().getFieldValue("spouse")).isEqualTo("Kerry");
assertThat(tb.getSpouse()).isNotNull();
});
}
@Test
@@ -1159,16 +1126,11 @@ public class DataBinderTests {
}
@Test
public void testValidatorNoErrors() {
public void testValidatorNoErrors() throws Exception {
TestBean tb = new TestBean();
tb.setAge(33);
tb.setName("Rod");
try {
tb.setTouchy("Rod");
}
catch (Exception e) {
fail("Should not throw any Exception");
}
tb.setTouchy("Rod"); // Should not throw
TestBean tb2 = new TestBean();
tb2.setAge(34);
tb.setSpouse(tb2);
@@ -1929,14 +1891,9 @@ public class DataBinderTests {
MutablePropertyValues mpvs = new MutablePropertyValues();
mpvs.add("friends[256]", "");
try {
binder.bind(mpvs);
fail("Should have thrown InvalidPropertyException");
}
catch (InvalidPropertyException ex) {
// expected
assertTrue(ex.getRootCause() instanceof IndexOutOfBoundsException);
}
assertThatExceptionOfType(InvalidPropertyException.class).isThrownBy(() ->
binder.bind(mpvs))
.satisfies(ex -> assertThat(ex.getRootCause()).isInstanceOf(IndexOutOfBoundsException.class));
}
@Test
@@ -1960,14 +1917,9 @@ public class DataBinderTests {
MutablePropertyValues mpvs = new MutablePropertyValues();
mpvs.add("friends[16]", "");
try {
binder.bind(mpvs);
fail("Should have thrown InvalidPropertyException");
}
catch (InvalidPropertyException ex) {
// expected
assertTrue(ex.getRootCause() instanceof IndexOutOfBoundsException);
}
assertThatExceptionOfType(InvalidPropertyException.class).isThrownBy(() ->
binder.bind(mpvs))
.satisfies(ex -> assertThat(ex.getRootCause()).isInstanceOf(IndexOutOfBoundsException.class));
}
@Test

View File

@@ -21,6 +21,7 @@ import org.junit.Test;
import org.springframework.lang.Nullable;
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;
@@ -35,17 +36,19 @@ import static org.junit.Assert.assertTrue;
*/
public class ValidationUtilsTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void testInvokeValidatorWithNullValidator() throws Exception {
TestBean tb = new TestBean();
Errors errors = new BeanPropertyBindingResult(tb, "tb");
ValidationUtils.invokeValidator(null, tb, errors);
assertThatIllegalArgumentException().isThrownBy(() ->
ValidationUtils.invokeValidator(null, tb, errors));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testInvokeValidatorWithNullErrors() throws Exception {
TestBean tb = new TestBean();
ValidationUtils.invokeValidator(new EmptyValidator(), tb, null);
assertThatIllegalArgumentException().isThrownBy(() ->
ValidationUtils.invokeValidator(new EmptyValidator(), tb, null));
}
@Test

View File

@@ -31,9 +31,9 @@ import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncAnnotationAdvisor;
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.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Juergen Hoeller
@@ -46,14 +46,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").contains("invalid"));
ac.close();
}
@@ -103,14 +98,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").contains("invalid"));
ac.close();
}

View File

@@ -18,6 +18,7 @@ package org.springframework.validation.beanvalidation;
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;
@@ -38,9 +39,9 @@ import org.springframework.scheduling.annotation.AsyncAnnotationAdvisor;
import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor;
import org.springframework.validation.annotation.Validated;
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
@@ -71,52 +72,20 @@ public class MethodValidationTests {
private void doTestProxyValidation(MyValidInterface 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

@@ -51,13 +51,13 @@ import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
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
@@ -74,12 +74,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);
@@ -101,12 +97,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);