提交 04d3f984 编写于 作者: C Chris Beams

polish: leading spaces -> tabs across .aop and .testsuite bundles

上级 b7cc5d24
#Fri Dec 12 11:37:26 PST 2008
eclipse.preferences.version=1
formatter_profile=org.eclipse.jdt.ui.default.eclipse_profile
formatter_settings_version=11
......@@ -41,8 +41,8 @@ public class MethodLocatingFactoryBean implements FactoryBean, BeanFactoryAware
/**
* Set the name of the bean to locate the {@link Method} on.
* <p>This property is required.
* @param targetBeanName the name of the bean to locate the {@link Method} on
* <p>This property is required.
* @param targetBeanName the name of the bean to locate the {@link Method} on
*/
public void setTargetBeanName(String targetBeanName) {
this.targetBeanName = targetBeanName;
......@@ -50,8 +50,8 @@ public class MethodLocatingFactoryBean implements FactoryBean, BeanFactoryAware
/**
* Set the name of the {@link Method} to locate.
* <p>This property is required.
* @param methodName the name of the {@link Method} to locate
* <p>This property is required.
* @param methodName the name of the {@link Method} to locate
*/
public void setMethodName(String methodName) {
this.methodName = methodName;
......
......@@ -238,19 +238,19 @@ public class AspectJAdviceParameterNameDiscovererTests {
}
@Test
public void testReferenceBinding() {
assertParameterNames(getMethod("onePrimitive"),"somepc(foo)",new String[] {"foo"});
}
public void testReferenceBinding() {
assertParameterNames(getMethod("onePrimitive"),"somepc(foo)",new String[] {"foo"});
}
@Test
public void testReferenceBindingWithAlternateTokenizations() {
assertParameterNames(getMethod("onePrimitive"),"call(bar *) && somepc(foo)",new String[] {"foo"});
assertParameterNames(getMethod("onePrimitive"),"somepc ( foo )",new String[] {"foo"});
assertParameterNames(getMethod("onePrimitive"),"somepc( foo)",new String[] {"foo"});
}
public void testReferenceBindingWithAlternateTokenizations() {
assertParameterNames(getMethod("onePrimitive"),"call(bar *) && somepc(foo)",new String[] {"foo"});
assertParameterNames(getMethod("onePrimitive"),"somepc ( foo )",new String[] {"foo"});
assertParameterNames(getMethod("onePrimitive"),"somepc( foo)",new String[] {"foo"});
}
protected Method getMethod(String name) {
protected Method getMethod(String name) {
// assumes no overloading of test methods...
Method[] candidates = this.getClass().getMethods();
for (int i = 0; i < candidates.length; i++) {
......
......@@ -29,7 +29,7 @@ import org.springframework.beans.TestBean;
*/
public class BeanNamePointcutMatchingTests {
@Test
@Test
public void testMatchingPointcuts() {
assertMatch("someName", "bean(someName)");
......@@ -64,7 +64,7 @@ public class BeanNamePointcutMatchingTests {
assertMatch("someName", "bean(someName) && !bean(someOtherName)");
}
@Test
@Test
public void testNonMatchingPointcuts() {
assertMisMatch("someName", "bean(someNamex)");
assertMisMatch("someName", "bean(someX*Name)");
......@@ -86,8 +86,8 @@ public class BeanNamePointcutMatchingTests {
matches(beanName, pcExpression));
}
private static boolean matches(final String beanName, String pcExpression) {
@SuppressWarnings("serial")
private static boolean matches(final String beanName, String pcExpression) {
@SuppressWarnings("serial")
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut() {
protected String getCurrentProxiedBeanName() {
return beanName;
......
......@@ -42,8 +42,8 @@ import org.springframework.beans.TestBean;
* @since 2.0
*/
public class MethodInvocationProceedingJoinPointTests {
@Test
@Test
public void testingBindingWithJoinPoint() {
try {
AbstractAspectJAdvice.currentJoinPoint();
......@@ -53,8 +53,8 @@ public class MethodInvocationProceedingJoinPointTests {
// expected
}
}
@Test
@Test
public void testingBindingWithProceedingJoinPoint() {
try {
AbstractAspectJAdvice.currentJoinPoint();
......@@ -64,8 +64,8 @@ public class MethodInvocationProceedingJoinPointTests {
// expected
}
}
@Test
@Test
public void testCanGetMethodSignatureFromJoinPoint() {
final Object raw = new TestBean();
// Will be set by advice during a method call
......@@ -133,8 +133,8 @@ public class MethodInvocationProceedingJoinPointTests {
// Any call will do
assertEquals("Advice reentrantly set age", newAge, itb.getAge());
}
@Test
@Test
public void testCanGetSourceLocationFromJoinPoint() {
final Object raw = new TestBean();
ProxyFactory pf = new ProxyFactory(raw);
......@@ -165,8 +165,8 @@ public class MethodInvocationProceedingJoinPointTests {
// Any call will do
itb.getAge();
}
@Test
@Test
public void testCanGetStaticPartFromJoinPoint() {
final Object raw = new TestBean();
ProxyFactory pf = new ProxyFactory(raw);
......
......@@ -35,7 +35,7 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory;
*/
public final class TypePatternClassFilterTests {
@Test
@Test
public void testInvalidPattern() {
try {
new TypePatternClassFilter("-");
......@@ -45,7 +45,7 @@ public final class TypePatternClassFilterTests {
}
}
@Test
@Test
public void testValidPatternMatching() {
TypePatternClassFilter tpcf = new TypePatternClassFilter("org.springframework.beans.*");
assertTrue("Must match: in package", tpcf.matches(TestBean.class));
......@@ -56,7 +56,7 @@ public final class TypePatternClassFilterTests {
assertFalse("Must be excluded: in wrong package", tpcf.matches(DefaultListableBeanFactory.class));
}
@Test
@Test
public void testSubclassMatching() {
TypePatternClassFilter tpcf = new TypePatternClassFilter("org.springframework.beans.ITestBean+");
assertTrue("Must match: in package", tpcf.matches(TestBean.class));
......@@ -66,7 +66,7 @@ public final class TypePatternClassFilterTests {
assertFalse("Must be excluded: not subclass", tpcf.matches(DefaultListableBeanFactory.class));
}
@Test
@Test
public void testAndOrNotReplacement() {
TypePatternClassFilter tpcf = new TypePatternClassFilter("java.lang.Object or java.lang.String");
assertFalse("matches Number",tpcf.matches(Number.class));
......@@ -80,12 +80,12 @@ public final class TypePatternClassFilterTests {
assertTrue("matches Double",tpcf.matches(Double.class));
}
@Test(expected=IllegalArgumentException.class)
@Test(expected=IllegalArgumentException.class)
public void testSetTypePatternWithNullArgument() throws Exception {
new TypePatternClassFilter(null);
new TypePatternClassFilter(null);
}
@Test(expected=IllegalStateException.class)
@Test(expected=IllegalStateException.class)
public void testInvocationOfMatchesMethodBlowsUpWhenNoTypePatternHasBeenSet() throws Exception {
new TypePatternClassFilter().matches(String.class);
}
......
......@@ -37,7 +37,7 @@ import org.springframework.beans.TestBean;
*/
public class ArgumentBindingTests {
@Test(expected=IllegalArgumentException.class)
@Test(expected=IllegalArgumentException.class)
public void testBindingInPointcutUsedByAdvice() {
TestBean tb = new TestBean();
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(tb);
......@@ -47,7 +47,7 @@ public class ArgumentBindingTests {
proxiedTestBean.setName("Supercalifragalisticexpialidocious"); // should throw
}
@Test(expected=IllegalStateException.class)
@Test(expected=IllegalStateException.class)
public void testAnnotationArgumentNameBinding() {
TransactionalBean tb = new TransactionalBean();
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(tb);
......@@ -57,7 +57,7 @@ public class ArgumentBindingTests {
proxiedTestBean.doInTransaction(); // should throw
}
@Test
@Test
public void testParameterNameDiscoverWithReferencePointcut() throws Exception {
AspectJAdviceParameterNameDiscoverer discoverer =
new AspectJAdviceParameterNameDiscoverer("somepc(formal) && set(* *)");
......
......@@ -32,12 +32,12 @@ import example.aspects.PerTargetAspect;
*/
public class AspectMetadataTests {
@Test(expected=IllegalArgumentException.class)
@Test(expected=IllegalArgumentException.class)
public void testNotAnAspect() {
new AspectMetadata(String.class,"someBean");
}
@Test
@Test
public void testSingletonAspect() {
AspectMetadata am = new AspectMetadata(ExceptionAspect.class,"someBean");
assertFalse(am.isPerThisOrPerTarget());
......@@ -45,7 +45,7 @@ public class AspectMetadataTests {
assertEquals(PerClauseKind.SINGLETON, am.getAjType().getPerClause().getKind());
}
@Test
@Test
public void testPerTargetAspect() {
AspectMetadata am = new AspectMetadata(PerTargetAspect.class,"someBean");
assertTrue(am.isPerThisOrPerTarget());
......@@ -53,7 +53,7 @@ public class AspectMetadataTests {
assertEquals(PerClauseKind.PERTARGET, am.getAjType().getPerClause().getKind());
}
@Test
@Test
public void testPerThisAspect() {
AspectMetadata am = new AspectMetadata(PerThisAspect.class,"someBean");
assertTrue(am.isPerThisOrPerTarget());
......
......@@ -30,13 +30,13 @@ import example.aspects.PerThisAspect;
*/
public class AspectProxyFactoryTests {
@Test(expected=IllegalArgumentException.class)
@Test(expected=IllegalArgumentException.class)
public void testWithNonAspect() {
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(new TestBean());
proxyFactory.addAspect(TestBean.class);
}
@Test
@Test
public void testWithSimpleAspect() throws Exception {
TestBean bean = new TestBean();
bean.setAge(2);
......@@ -46,7 +46,7 @@ public class AspectProxyFactoryTests {
assertEquals("Multiplication did not occur", bean.getAge() * 2, proxy.getAge());
}
@Test
@Test
public void testWithPerThisAspect() throws Exception {
TestBean bean1 = new TestBean();
TestBean bean2 = new TestBean();
......
......@@ -29,7 +29,7 @@ import org.springframework.core.io.ClassPathResource;
*/
public class AopNamespaceHandlerPointcutErrorTests {
@Test
@Test
public void testDuplicatePointcutConfig() {
try {
new XmlBeanFactory(new ClassPathResource(
......@@ -40,8 +40,8 @@ public class AopNamespaceHandlerPointcutErrorTests {
assertTrue(ex.contains(BeanDefinitionParsingException.class));
}
}
@Test
@Test
public void testMissingPointcutConfig() {
try {
new XmlBeanFactory(new ClassPathResource(
......
......@@ -30,7 +30,7 @@ import org.springframework.core.io.ClassPathResource;
*/
public final class TopLevelAopTagTests {
@Test
@Test
public void testParse() throws Exception {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
......
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.framework;
/**
......@@ -22,7 +22,7 @@
* @author Rod Johnson
*/
public class DefaultLockable implements Lockable {
private boolean locked;
public void lock() {
......
......@@ -32,54 +32,54 @@ import org.springframework.util.StopWatch;
* @since 2.0
*/
public class IntroductionBenchmarkTests {
private static final int EXPECTED_COMPARE = 13;
/** Increase this if you want meaningful results! */
private static final int INVOCATIONS = 100000;
@SuppressWarnings("serial")
public static class SimpleCounterIntroduction extends DelegatingIntroductionInterceptor implements Counter {
public int getCount() {
return EXPECTED_COMPARE;
}
}
public static interface Counter {
int getCount();
}
@Test
public void timeManyInvocations() {
StopWatch sw = new StopWatch();
TestBean target = new TestBean();
ProxyFactory pf = new ProxyFactory(target);
pf.setProxyTargetClass(false);
pf.addAdvice(new SimpleCounterIntroduction());
ITestBean proxy = (ITestBean) pf.getProxy();
Counter counter = (Counter) proxy;
sw.start(INVOCATIONS + " invocations on proxy, not hitting introduction");
for (int i = 0; i < INVOCATIONS; i++) {
proxy.getAge();
}
sw.stop();
sw.start(INVOCATIONS + " invocations on proxy, hitting introduction");
for (int i = 0; i < INVOCATIONS; i++) {
counter.getCount();
}
sw.stop();
sw.start(INVOCATIONS + " invocations on target");
for (int i = 0; i < INVOCATIONS; i++) {
target.getAge();
}
sw.stop();
System.out.println(sw.prettyPrint());
}
sw.start(INVOCATIONS + " invocations on proxy, not hitting introduction");
for (int i = 0; i < INVOCATIONS; i++) {
proxy.getAge();
}
sw.stop();
sw.start(INVOCATIONS + " invocations on proxy, hitting introduction");
for (int i = 0; i < INVOCATIONS; i++) {
counter.getCount();
}
sw.stop();
sw.start(INVOCATIONS + " invocations on target");
for (int i = 0; i < INVOCATIONS; i++) {
target.getAge();
}
sw.stop();
System.out.println(sw.prettyPrint());
}
}
......@@ -41,7 +41,7 @@ import org.springframework.aop.framework.MethodCounter;
*/
public class ThrowsAdviceInterceptorTests {
@Test
@Test
public void testNoHandlerMethods() {
Object o = new Object();
try {
......@@ -52,8 +52,8 @@ public class ThrowsAdviceInterceptorTests {
// Ok
}
}
@Test
@Test
public void testNotInvoked() throws Throwable {
MyThrowsHandler th = new MyThrowsHandler();
ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th);
......@@ -65,8 +65,8 @@ public class ThrowsAdviceInterceptorTests {
assertEquals(0, th.getCalls());
verify(mi);
}
@Test
@Test
public void testNoHandlerMethodForThrowable() throws Throwable {
MyThrowsHandler th = new MyThrowsHandler();
ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th);
......@@ -85,8 +85,8 @@ public class ThrowsAdviceInterceptorTests {
assertEquals(0, th.getCalls());
verify(mi);
}
@Test
@Test
public void testCorrectHandlerUsed() throws Throwable {
MyThrowsHandler th = new MyThrowsHandler();
ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th);
......@@ -108,8 +108,8 @@ public class ThrowsAdviceInterceptorTests {
assertEquals(1, th.getCalls("ioException"));
verify(mi);
}
@Test
@Test
public void testCorrectHandlerUsedForSubclass() throws Throwable {
MyThrowsHandler th = new MyThrowsHandler();
ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th);
......@@ -129,11 +129,11 @@ public class ThrowsAdviceInterceptorTests {
assertEquals(1, th.getCalls("remoteException"));
verify(mi);
}
@Test
@Test
public void testHandlerMethodThrowsException() throws Throwable {
final Throwable t = new Throwable();
@SuppressWarnings("serial")
MyThrowsHandler th = new MyThrowsHandler() {
public void afterThrowing(RemoteException ex) throws Throwable {
......@@ -141,7 +141,7 @@ public class ThrowsAdviceInterceptorTests {
throw t;
}
};
ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th);
// Extends RemoteException
TransactionRolledbackException ex = new TransactionRolledbackException();
......@@ -159,9 +159,9 @@ public class ThrowsAdviceInterceptorTests {
assertEquals(1, th.getCalls("remoteException"));
verify(mi);
}
@SuppressWarnings("serial")
private static class MyThrowsHandler extends MethodCounter implements ThrowsAdvice {
private static class MyThrowsHandler extends MethodCounter implements ThrowsAdvice {
// Full method signature
public void afterThrowing(Method m, Object[] args, Object target, IOException ex) {
count("ioException");
......@@ -169,11 +169,11 @@ public class ThrowsAdviceInterceptorTests {
public void afterThrowing(RemoteException ex) throws Throwable {
count("remoteException");
}
/** Not valid, wrong number of arguments */
public void afterThrowing(Method m, Exception ex) throws Throwable {
throw new UnsupportedOperationException("Shouldn't be called");
}
}
}
......@@ -27,11 +27,11 @@ public class AuthenticationLogger {
public void logAuthenticationAttempt(String username) {
System.out.println("User [" + username + "] attempting to authenticate");
}
}
class SecurityManager {
public boolean authenticate(String username, String password) {
return false;
}
public boolean authenticate(String username, String password) {
return false;
}
}
......@@ -30,7 +30,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
*/
public class OverloadedAdviceTests {
@Test
@Test
public void testExceptionOnConfigParsingWithMismatchedAdviceMethod() {
try {
new ClassPathXmlApplicationContext("org/springframework/aop/aspectj/overloaded-advice-tests.xml");
......@@ -42,8 +42,8 @@ public class OverloadedAdviceTests {
cause.getMessage().indexOf("invalidAbsoluteTypeName") != -1);
}
}
@Test
@Test
public void testExceptionOnConfigParsingWithAmbiguousAdviceMethod() {
try {
new ClassPathXmlApplicationContext("org/springframework/aop/aspectj/ambiguous-advice-tests.xml");
......
......@@ -33,22 +33,22 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
*/
public class PropertyDependentAspectTests {
@Test
@Test
public void testPropertyDependentAspectWithPropertyDeclaredBeforeAdvice() throws Exception {
checkXmlAspect("org/springframework/aop/aspectj/property-dependent-aspect-property-before-aspect-test.xml");
}
@Test
@Test
public void testPropertyDependentAspectWithPropertyDeclaredAfterAdvice() throws Exception {
checkXmlAspect("org/springframework/aop/aspectj/property-dependent-aspect-property-after-aspect-test.xml");
}
@Test
@Test
public void testPropertyDependentAtAspectJAspectWithPropertyDeclaredBeforeAdvice() throws Exception {
checkAtAspectJAspect("org/springframework/aop/aspectj/property-dependent-atAspectJ-aspect-property-before-aspect-test.xml");
}
@Test
@Test
public void testPropertyDependentAtAspectJAspectWithPropertyDeclaredAfterAdvice() throws Exception {
checkAtAspectJAspect("org/springframework/aop/aspectj/property-dependent-atAspectJ-aspect-property-after-aspect-test.xml");
}
......
......@@ -24,18 +24,18 @@ import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class AdviceUsingThisJoinPoint {
private String lastEntry = "";
public String getLastMethodEntered() {
return this.lastEntry;
}
@Pointcut("execution(* *(..))")
public void methodExecution() {}
@Before("methodExecution()")
public void entryTrace(JoinPoint jp) {
this.lastEntry = jp.toString();
}
private String lastEntry = "";
public String getLastMethodEntered() {
return this.lastEntry;
}
@Pointcut("execution(* *(..))")
public void methodExecution() {}
@Before("methodExecution()")
public void entryTrace(JoinPoint jp) {
this.lastEntry = jp.toString();
}
}
......@@ -31,7 +31,7 @@ import java.io.IOException;
*/
public class AtAspectJAfterThrowingTests {
@Test
@Test
public void testAccessThrowable() throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("afterThrowingAdviceTests.xml", getClass());
......
......@@ -27,7 +27,7 @@ import org.springframework.beans.ITestBean;
*/
public class AopNamespaceHandlerProxyTargetClassTests extends AopNamespaceHandlerTests {
@Test
@Test
public void testIsClassProxy() {
ITestBean bean = getTestBean();
assertTrue("Should be a CGLIB proxy", AopUtils.isCglibProxy(bean));
......
......@@ -24,7 +24,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
*/
public class PrototypeProxyTests {
@Test
@Test
public void testInjectionBeforeWrappingCheckDoesNotKickInForPrototypeProxy() {
new ClassPathXmlApplicationContext("prototypeProxy.xml", getClass());
}
......
......@@ -802,7 +802,7 @@ public abstract class AbstractAopProxyTests {
ProxyFactory pc = new ProxyFactory(target);
@SuppressWarnings("serial")
class MyDi extends DelegatingIntroductionInterceptor implements TimeStamped {
class MyDi extends DelegatingIntroductionInterceptor implements TimeStamped {
/**
* @see org.springframework.aop.framework.TimeStamped#getTimeStamp()
*/
......@@ -1266,11 +1266,11 @@ public abstract class AbstractAopProxyTests {
public void releaseTarget(Object target) throws Exception {
}
});
// Just test anything: it will fail if context wasn't found
assertEquals(0, proxy.getAge());
}
@Test
public void testEquals() {
IOther a = new AllInstancesAreEqual();
......@@ -1328,7 +1328,7 @@ public abstract class AbstractAopProxyTests {
assertEquals(1, cba.getCalls());
assertEquals(26, proxied.getAge());
}
@Test
public void testUserAttributes() throws Throwable {
class MapAwareMethodInterceptor implements MethodInterceptor {
......@@ -1362,7 +1362,7 @@ public abstract class AbstractAopProxyTests {
Map<String, String> finalExpected = new HashMap<String, String>(firstValuesToAdd);
finalExpected.putAll(secondValuesToAdd);
MapAwareMethodInterceptor mami6 = new MapAwareMethodInterceptor(finalExpected, secondValuesToAdd);
pc.addAdvice(mami1);
pc.addAdvice(mami2);
pc.addAdvice(mami3);
......@@ -1471,7 +1471,7 @@ public abstract class AbstractAopProxyTests {
}
}
SummingAfterAdvice aa = new SummingAfterAdvice();
@SuppressWarnings("serial")
@SuppressWarnings("serial")
Advisor matchesInt = new StaticMethodMatcherPointcutAdvisor(aa) {
public boolean matches(Method m, Class<?> targetClass) {
return m.getReturnType() == int.class;
......
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.framework;
/**
......@@ -22,7 +22,7 @@
* @author Rod Johnson
*/
public class DefaultLockable implements Lockable {
private boolean locked;
public void lock() {
......
......@@ -59,7 +59,7 @@ import org.springframework.util.SerializationTestUtils;
* @since 13.03.2003
*/
public class ProxyFactoryBeanTests extends TestCase {
private BeanFactory factory;
protected void setUp() throws Exception {
......@@ -72,7 +72,7 @@ public class ProxyFactoryBeanTests extends TestCase {
ITestBean test1 = (ITestBean) factory.getBean("test1");
assertTrue("test1 is a dynamic proxy", Proxy.isProxyClass(test1.getClass()));
}
public void testIsDynamicProxyWhenInterfaceSpecifiedForPrototype() {
ITestBean test1 = (ITestBean) factory.getBean("test2");
assertTrue("test2 is a dynamic proxy", Proxy.isProxyClass(test1.getClass()));
......@@ -97,7 +97,7 @@ public class ProxyFactoryBeanTests extends TestCase {
// Now with conversion from arbitrary bean to a TargetSource
testDoubleTargetSourceIsRejected("arbitraryTarget");
}
private void testDoubleTargetSourceIsRejected(String name) {
try {
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("proxyFactoryDoubleTargetSourceTests.xml", getClass()));
......@@ -111,7 +111,7 @@ public class ProxyFactoryBeanTests extends TestCase {
assertTrue(aex.getMessage().indexOf("TargetSource") != -1);
}
}
public void testTargetSourceNotAtEndOfInterceptorNamesIsRejected() {
try {
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("proxyFactoryTargetSourceNotLastTests.xml", getClass()));
......@@ -124,22 +124,22 @@ public class ProxyFactoryBeanTests extends TestCase {
assertTrue(aex.getMessage().indexOf("interceptorNames") != -1);
}
}
public void testGetObjectTypeWithDirectTarget() {
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("proxyFactoryTargetSourceTests.xml", getClass()));
// We have a counting before advice here
CountingBeforeAdvice cba = (CountingBeforeAdvice) bf.getBean("countingBeforeAdvice");
assertEquals(0, cba.getCalls());
ITestBean tb = (ITestBean) bf.getBean("directTarget");
assertTrue(tb.getName().equals("Adam"));
assertEquals(1, cba.getCalls());
ProxyFactoryBean pfb = (ProxyFactoryBean) bf.getBean("&directTarget");
assertTrue("Has correct object type", TestBean.class.isAssignableFrom(pfb.getObjectType()));
}
public void testGetObjectTypeWithTargetViaTargetSource() {
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("proxyFactoryTargetSourceTests.xml", getClass()));
ITestBean tb = (ITestBean) bf.getBean("viaTargetSource");
......@@ -147,7 +147,7 @@ public class ProxyFactoryBeanTests extends TestCase {
ProxyFactoryBean pfb = (ProxyFactoryBean) bf.getBean("&viaTargetSource");
assertTrue("Has correct object type", TestBean.class.isAssignableFrom(pfb.getObjectType()));
}
public void testGetObjectTypeWithNoTargetOrTargetSource() {
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("proxyFactoryTargetSourceTests.xml", getClass()));
......@@ -162,7 +162,7 @@ public class ProxyFactoryBeanTests extends TestCase {
FactoryBean pfb = (ProxyFactoryBean) bf.getBean("&noTarget");
assertTrue("Has correct object type", ITestBean.class.isAssignableFrom(pfb.getObjectType()));
}
/**
* The instances are equal, but do not have object identity.
* Interceptors and interfaces and the target are the same.
......@@ -189,7 +189,7 @@ public class ProxyFactoryBeanTests extends TestCase {
assertEquals(test1_1.getAge(), test1.getAge());
assertEquals(di.getCount(), 3);
}
public void testPrototypeInstancesAreNotEqual() {
assertTrue("Has correct object type", ITestBean.class.isAssignableFrom(factory.getType("prototype")));
ITestBean test2 = (ITestBean) factory.getBean("prototype");
......@@ -207,9 +207,9 @@ public class ProxyFactoryBeanTests extends TestCase {
private Object testPrototypeInstancesAreIndependent(String beanName) {
// Initial count value set in bean factory XML
int INITIAL_COUNT = 10;
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("prototypeTests.xml", getClass()));
// Check it works without AOP
SideEffectBean raw = (SideEffectBean) bf.getBean("prototypeTarget");
assertEquals(INITIAL_COUNT, raw.getCount() );
......@@ -217,7 +217,7 @@ public class ProxyFactoryBeanTests extends TestCase {
assertEquals(INITIAL_COUNT+1, raw.getCount() );
raw = (SideEffectBean) bf.getBean("prototypeTarget");
assertEquals(INITIAL_COUNT, raw.getCount() );
// Now try with advised instances
SideEffectBean prototype2FirstInstance = (SideEffectBean) bf.getBean(beanName);
assertEquals(INITIAL_COUNT, prototype2FirstInstance.getCount() );
......@@ -228,16 +228,16 @@ public class ProxyFactoryBeanTests extends TestCase {
assertFalse("Prototypes are not ==", prototype2FirstInstance == prototype2SecondInstance);
assertEquals(INITIAL_COUNT, prototype2SecondInstance.getCount() );
assertEquals(INITIAL_COUNT + 1, prototype2FirstInstance.getCount() );
return prototype2FirstInstance;
}
public void testCglibPrototypeInstance() {
Object prototype = testPrototypeInstancesAreIndependent("cglibPrototype");
assertTrue("It's a cglib proxy", AopUtils.isCglibProxy(prototype));
assertFalse("It's not a dynamic proxy", AopUtils.isJdkDynamicProxy(prototype));
}
/**
* Test invoker is automatically added to manipulate target.
*/
......@@ -262,7 +262,7 @@ public class ProxyFactoryBeanTests extends TestCase {
ITestBean tb = (ITestBean) factory.getBean("test1");
// no exception
tb.hashCode();
final Exception ex = new UnsupportedOperationException("invoke");
// Add evil interceptor to head of list
config.addAdvice(0, new MethodInterceptor() {
......@@ -271,7 +271,7 @@ public class ProxyFactoryBeanTests extends TestCase {
}
});
assertEquals("Have correct advisor count", 2, config.getAdvisors().length);
tb = (ITestBean) factory.getBean("test1");
try {
// Will fail now
......@@ -282,14 +282,14 @@ public class ProxyFactoryBeanTests extends TestCase {
assertTrue(thrown == ex);
}
}
public static class DependsOnITestBean {
public final ITestBean tb;
public DependsOnITestBean(ITestBean tb) {
this.tb = tb;
}
}
/**
* Test that inner bean for target means that we can use
* autowire without ambiguity from target and proxy
......@@ -302,7 +302,7 @@ public class ProxyFactoryBeanTests extends TestCase {
DependsOnITestBean doit = (DependsOnITestBean) bf.getBean("autowireCheck");
assertSame(itb, doit.tb);
}
/**
* Try adding and removing interfaces and interceptors on prototype.
* Changes will only affect future references obtained from the factory.
......@@ -315,7 +315,7 @@ public class ProxyFactoryBeanTests extends TestCase {
}
catch (ClassCastException ex) {
}
ProxyFactoryBean config = (ProxyFactoryBean) factory.getBean("&test2");
long time = 666L;
TimestampIntroductionInterceptor ti = new TimestampIntroductionInterceptor();
......@@ -324,28 +324,28 @@ public class ProxyFactoryBeanTests extends TestCase {
int oldCount = config.getAdvisors().length;
config.addAdvisor(0, new DefaultIntroductionAdvisor(ti, TimeStamped.class));
assertTrue(config.getAdvisors().length == oldCount + 1);
TimeStamped ts = (TimeStamped) factory.getBean("test2");
assertEquals(time, ts.getTimeStamp());
// Can remove
config.removeAdvice(ti);
assertTrue(config.getAdvisors().length == oldCount);
// Check no change on existing object reference
assertTrue(ts.getTimeStamp() == time);
try {
ts = (TimeStamped) factory.getBean("test2");
fail("Should no longer implement TimeStamped");
}
catch (ClassCastException ex) {
}
// Now check non-effect of removing interceptor that isn't there
config.removeAdvice(new DebugInterceptor());
assertTrue(config.getAdvisors().length == oldCount);
ITestBean it = (ITestBean) ts;
DebugInterceptor debugInterceptor = new DebugInterceptor();
config.addAdvice(0, debugInterceptor);
......@@ -357,15 +357,15 @@ public class ProxyFactoryBeanTests extends TestCase {
assertEquals(1, debugInterceptor.getCount());
config.removeAdvice(debugInterceptor);
it.getSpouse();
// Still invoked wiht old reference
assertEquals(2, debugInterceptor.getCount());
// not invoked with new object
it = (ITestBean) factory.getBean("test2");
it.getSpouse();
assertEquals(2, debugInterceptor.getCount());
// Our own timestamped reference should still work
assertEquals(time, ts.getTimeStamp());
}
......@@ -400,7 +400,7 @@ public class ProxyFactoryBeanTests extends TestCase {
assertTrue(PointcutForVoid.methodNames.get(0).equals("setAge"));
assertTrue(PointcutForVoid.methodNames.get(1).equals("setName"));
}
public void testCanAddThrowsAdviceWithoutAdvisor() throws Throwable {
BeanFactory f = new XmlBeanFactory(new ClassPathResource("throwsAdvice.xml", getClass()));
MyThrowsHandler th = (MyThrowsHandler) f.getBean("throwsAdvice");
......@@ -423,7 +423,7 @@ public class ProxyFactoryBeanTests extends TestCase {
}
// No throws handler method: count should still be 0
assertEquals(0, th.getCalls());
// Handler knows how to handle this exception
expected = new FileNotFoundException();
try {
......@@ -449,7 +449,7 @@ public class ProxyFactoryBeanTests extends TestCase {
// Ok
}
}
public void testNoInterceptorNamesWithTarget() {
ITestBean tb = (ITestBean) factory.getBean("noInterceptorNamesWithoutTarget");
}
......@@ -489,17 +489,17 @@ public class ProxyFactoryBeanTests extends TestCase {
public void testGlobalsCanAddAspectInterfaces() {
AddedGlobalInterface agi = (AddedGlobalInterface) factory.getBean("autoInvoker");
assertTrue(agi.globalsAdded() == -1);
ProxyFactoryBean pfb = (ProxyFactoryBean) factory.getBean("&validGlobals");
// Trigger lazy initialization.
pfb.getObject();
// 2 globals + 2 explicit
assertEquals("Have 2 globals and 2 explicit advisors", 3, pfb.getAdvisors().length);
ApplicationListener l = (ApplicationListener) factory.getBean("validGlobals");
agi = (AddedGlobalInterface) l;
assertTrue(agi.globalsAdded() == -1);
try {
agi = (AddedGlobalInterface) factory.getBean("test1");
fail("Aspect interface should't be implemeneted without globals");
......@@ -516,14 +516,14 @@ public class ProxyFactoryBeanTests extends TestCase {
assertEquals(p, p2);
assertNotSame(p, p2);
assertEquals("serializableSingleton", p2.getName());
// Add unserializable advice
Advice nop = new NopInterceptor();
((Advised) p).addAdvice(nop);
// Check it still works
assertEquals(p2.getName(), p2.getName());
assertFalse("Not serializable because an interceptor isn't serializable", SerializationTestUtils.isSerializable(p));
// Remove offending interceptor...
assertTrue(((Advised) p).removeAdvice(nop));
assertTrue("Serializable again because offending interceptor was removed", SerializationTestUtils.isSerializable(p));
......@@ -614,7 +614,7 @@ public class ProxyFactoryBeanTests extends TestCase {
fail("did not expect LockedException");
}
}
/**
* Simple test of a ProxyFactoryBean that has an inner bean as target that specifies autowiring.
* Checks for correct use of getType() by bean factory.
......@@ -623,12 +623,12 @@ public class ProxyFactoryBeanTests extends TestCase {
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("proxyFactoryBeanAutowiringTests.xml", getClass()));
bf.getBean("testBean");
}
public void testFrozenFactoryBean() {
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("frozenProxyFactoryBean.xml", getClass()));
Advised advised = (Advised)bf.getBean("frozen");
assertTrue("The proxy should be frozen", advised.isFrozen());
Advised advised = (Advised)bf.getBean("frozen");
assertTrue("The proxy should be frozen", advised.isFrozen());
}
public void testDetectsInterfaces() throws Exception {
......@@ -643,13 +643,13 @@ public class ProxyFactoryBeanTests extends TestCase {
* Fires only on void methods. Saves list of methods intercepted.
*/
public static class PointcutForVoid extends DefaultPointcutAdvisor {
public static List methodNames = new LinkedList();
public static void reset() {
methodNames.clear();
}
public PointcutForVoid() {
setAdvice(new MethodInterceptor() {
public Object invoke(MethodInvocation invocation) throws Throwable {
......@@ -695,7 +695,7 @@ public class ProxyFactoryBeanTests extends TestCase {
public static class GlobalIntroductionAdvice implements IntroductionAdvisor {
private IntroductionInterceptor gi = new GlobalAspectInterfaceInterceptor();
public ClassFilter getClassFilter() {
......@@ -713,9 +713,9 @@ public class ProxyFactoryBeanTests extends TestCase {
public boolean isPerInstance() {
return false;
}
public void validateInterfaces() {
}
}
}
......@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
......@@ -33,24 +33,24 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
*/
public class AdvisorAdapterRegistrationTests {
@Test
public void testAdvisorAdapterRegistrationManagerNotPresentInContext() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("/org/springframework/aop/framework/adapter/withoutBPPContext.xml");
ITestBean tb = (ITestBean) ctx.getBean("testBean");
@Test
public void testAdvisorAdapterRegistrationManagerNotPresentInContext() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("/org/springframework/aop/framework/adapter/withoutBPPContext.xml");
ITestBean tb = (ITestBean) ctx.getBean("testBean");
// just invoke any method to see if advice fired
try {
try {
tb.getName();
fail("Should throw UnknownAdviceTypeException");
}
catch (UnknownAdviceTypeException ex) {
// expected
// expected
assertEquals(0, getAdviceImpl(tb).getInvocationCounter());
}
}
@Test
@Test
public void testAdvisorAdapterRegistrationManagerPresentInContext() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("/org/springframework/aop/framework/adapter/withBPPContext.xml");
ApplicationContext ctx = new ClassPathXmlApplicationContext("/org/springframework/aop/framework/adapter/withBPPContext.xml");
ITestBean tb = (ITestBean) ctx.getBean("testBean");
// just invoke any method to see if advice fired
try {
......
......@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
......@@ -28,87 +28,87 @@ import org.easymock.MockControl;
*/
public final class DebugInterceptorTests extends TestCase {
public void testSunnyDayPathLogsCorrectly() throws Throwable {
MockControl mockLog = MockControl.createControl(Log.class);
final Log log = (Log) mockLog.getMock();
public void testSunnyDayPathLogsCorrectly() throws Throwable {
MockControl mockLog = MockControl.createControl(Log.class);
final Log log = (Log) mockLog.getMock();
MockControl mockMethodInvocation = MockControl.createControl(MethodInvocation.class);
MethodInvocation methodInvocation = (MethodInvocation) mockMethodInvocation.getMock();
MockControl mockMethodInvocation = MockControl.createControl(MethodInvocation.class);
MethodInvocation methodInvocation = (MethodInvocation) mockMethodInvocation.getMock();
log.isTraceEnabled();
mockLog.setReturnValue(true);
log.trace("Some tracing output");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
methodInvocation.proceed();
mockMethodInvocation.setReturnValue(null);
log.trace("Some more tracing output");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
mockLog.setVoidCallable();
log.isTraceEnabled();
mockLog.setReturnValue(true);
log.trace("Some tracing output");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
methodInvocation.proceed();
mockMethodInvocation.setReturnValue(null);
log.trace("Some more tracing output");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
mockLog.setVoidCallable();
mockMethodInvocation.replay();
mockLog.replay();
mockMethodInvocation.replay();
mockLog.replay();
DebugInterceptor interceptor = new StubDebugInterceptor(log);
interceptor.invoke(methodInvocation);
checkCallCountTotal(interceptor);
DebugInterceptor interceptor = new StubDebugInterceptor(log);
interceptor.invoke(methodInvocation);
checkCallCountTotal(interceptor);
mockLog.verify();
mockMethodInvocation.verify();
}
mockLog.verify();
mockMethodInvocation.verify();
}
public void testExceptionPathStillLogsCorrectly() throws Throwable {
MockControl mockLog = MockControl.createControl(Log.class);
final Log log = (Log) mockLog.getMock();
public void testExceptionPathStillLogsCorrectly() throws Throwable {
MockControl mockLog = MockControl.createControl(Log.class);
final Log log = (Log) mockLog.getMock();
MockControl mockMethodInvocation = MockControl.createControl(MethodInvocation.class);
final MethodInvocation methodInvocation = (MethodInvocation) mockMethodInvocation.getMock();
MockControl mockMethodInvocation = MockControl.createControl(MethodInvocation.class);
final MethodInvocation methodInvocation = (MethodInvocation) mockMethodInvocation.getMock();
log.isTraceEnabled();
mockLog.setReturnValue(true);
log.trace("Some tracing output");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
methodInvocation.proceed();
IllegalArgumentException exception = new IllegalArgumentException();
mockMethodInvocation.setThrowable(exception);
log.trace("Some more tracing output", exception);
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
mockLog.setVoidCallable();
log.isTraceEnabled();
mockLog.setReturnValue(true);
log.trace("Some tracing output");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
methodInvocation.proceed();
IllegalArgumentException exception = new IllegalArgumentException();
mockMethodInvocation.setThrowable(exception);
log.trace("Some more tracing output", exception);
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
mockLog.setVoidCallable();
mockMethodInvocation.replay();
mockLog.replay();
mockMethodInvocation.replay();
mockLog.replay();
DebugInterceptor interceptor = new StubDebugInterceptor(log);
try {
interceptor.invoke(methodInvocation);
fail("Must have propagated the IllegalArgumentException.");
} catch (IllegalArgumentException expected) {
}
checkCallCountTotal(interceptor);
DebugInterceptor interceptor = new StubDebugInterceptor(log);
try {
interceptor.invoke(methodInvocation);
fail("Must have propagated the IllegalArgumentException.");
} catch (IllegalArgumentException expected) {
}
checkCallCountTotal(interceptor);
mockLog.verify();
mockMethodInvocation.verify();
}
mockLog.verify();
mockMethodInvocation.verify();
}
private void checkCallCountTotal(DebugInterceptor interceptor) {
assertEquals("Intercepted call count not being incremented correctly", 1, interceptor.getCount());
}
private void checkCallCountTotal(DebugInterceptor interceptor) {
assertEquals("Intercepted call count not being incremented correctly", 1, interceptor.getCount());
}
private static final class StubDebugInterceptor extends DebugInterceptor {
private static final class StubDebugInterceptor extends DebugInterceptor {
private final Log log;
private final Log log;
public StubDebugInterceptor(Log log) {
super(true);
this.log = log;
}
public StubDebugInterceptor(Log log) {
super(true);
this.log = log;
}
protected Log getLoggerForInvocation(MethodInvocation invocation) {
return log;
}
protected Log getLoggerForInvocation(MethodInvocation invocation) {
return log;
}
}
}
}
......@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
......@@ -30,72 +30,72 @@ import java.lang.reflect.Method;
*/
public final class SimpleTraceInterceptorTests extends TestCase {
public void testSunnyDayPathLogsCorrectly() throws Throwable {
MockControl mockLog = MockControl.createControl(Log.class);
Log log = (Log) mockLog.getMock();
MockControl mockMethodInvocation = MockControl.createControl(MethodInvocation.class);
MethodInvocation methodInvocation = (MethodInvocation) mockMethodInvocation.getMock();
Method toString = String.class.getMethod("toString", new Class[]{});
methodInvocation.getMethod();
mockMethodInvocation.setReturnValue(toString);
methodInvocation.getThis();
mockMethodInvocation.setReturnValue(this);
log.trace("Some tracing output");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
methodInvocation.proceed();
mockMethodInvocation.setReturnValue(null);
log.trace("Some more tracing output");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
mockLog.setVoidCallable();
mockMethodInvocation.replay();
mockLog.replay();
SimpleTraceInterceptor interceptor = new SimpleTraceInterceptor(true);
interceptor.invokeUnderTrace(methodInvocation, log);
mockLog.verify();
mockMethodInvocation.verify();
}
public void testExceptionPathStillLogsCorrectly() throws Throwable {
MockControl mockLog = MockControl.createControl(Log.class);
final Log log = (Log) mockLog.getMock();
MockControl mockMethodInvocation = MockControl.createControl(MethodInvocation.class);
final MethodInvocation methodInvocation = (MethodInvocation) mockMethodInvocation.getMock();
Method toString = String.class.getMethod("toString", new Class[]{});
methodInvocation.getMethod();
mockMethodInvocation.setReturnValue(toString);
methodInvocation.getThis();
mockMethodInvocation.setReturnValue(this);
log.trace("Some tracing output");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
methodInvocation.proceed();
IllegalArgumentException exception = new IllegalArgumentException();
mockMethodInvocation.setThrowable(exception);
log.trace("Some more tracing output", exception);
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
mockLog.setVoidCallable();
mockMethodInvocation.replay();
mockLog.replay();
final SimpleTraceInterceptor interceptor = new SimpleTraceInterceptor(true);
try {
interceptor.invokeUnderTrace(methodInvocation, log);
fail("Must have propagated the IllegalArgumentException.");
} catch (IllegalArgumentException expected) {
}
mockLog.verify();
mockMethodInvocation.verify();
}
public void testSunnyDayPathLogsCorrectly() throws Throwable {
MockControl mockLog = MockControl.createControl(Log.class);
Log log = (Log) mockLog.getMock();
MockControl mockMethodInvocation = MockControl.createControl(MethodInvocation.class);
MethodInvocation methodInvocation = (MethodInvocation) mockMethodInvocation.getMock();
Method toString = String.class.getMethod("toString", new Class[]{});
methodInvocation.getMethod();
mockMethodInvocation.setReturnValue(toString);
methodInvocation.getThis();
mockMethodInvocation.setReturnValue(this);
log.trace("Some tracing output");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
methodInvocation.proceed();
mockMethodInvocation.setReturnValue(null);
log.trace("Some more tracing output");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
mockLog.setVoidCallable();
mockMethodInvocation.replay();
mockLog.replay();
SimpleTraceInterceptor interceptor = new SimpleTraceInterceptor(true);
interceptor.invokeUnderTrace(methodInvocation, log);
mockLog.verify();
mockMethodInvocation.verify();
}
public void testExceptionPathStillLogsCorrectly() throws Throwable {
MockControl mockLog = MockControl.createControl(Log.class);
final Log log = (Log) mockLog.getMock();
MockControl mockMethodInvocation = MockControl.createControl(MethodInvocation.class);
final MethodInvocation methodInvocation = (MethodInvocation) mockMethodInvocation.getMock();
Method toString = String.class.getMethod("toString", new Class[]{});
methodInvocation.getMethod();
mockMethodInvocation.setReturnValue(toString);
methodInvocation.getThis();
mockMethodInvocation.setReturnValue(this);
log.trace("Some tracing output");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
methodInvocation.proceed();
IllegalArgumentException exception = new IllegalArgumentException();
mockMethodInvocation.setThrowable(exception);
log.trace("Some more tracing output", exception);
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
mockLog.setVoidCallable();
mockMethodInvocation.replay();
mockLog.replay();
final SimpleTraceInterceptor interceptor = new SimpleTraceInterceptor(true);
try {
interceptor.invokeUnderTrace(methodInvocation, log);
fail("Must have propagated the IllegalArgumentException.");
} catch (IllegalArgumentException expected) {
}
mockLog.verify();
mockMethodInvocation.verify();
}
}
......@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
......@@ -50,12 +50,12 @@ public class DelegatingIntroductionInterceptorTests extends TestCase {
// OK
}
}
public void testIntroductionInterceptorWithDelegation() throws Exception {
TestBean raw = new TestBean();
assertTrue(! (raw instanceof TimeStamped));
ProxyFactory factory = new ProxyFactory(raw);
MockControl tsControl = MockControl.createControl(TimeStamped.class);
TimeStamped ts = (TimeStamped) tsControl.getMock();
ts.getTimeStamp();
......@@ -64,13 +64,13 @@ public class DelegatingIntroductionInterceptorTests extends TestCase {
tsControl.replay();
factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts)));
TimeStamped tsp = (TimeStamped) factory.getProxy();
assertTrue(tsp.getTimeStamp() == timestamp);
tsControl.verify();
}
public void testIntroductionInterceptorWithInterfaceHierarchy() throws Exception {
TestBean raw = new TestBean();
assertTrue(! (raw instanceof SubTimeStamped));
......@@ -121,24 +121,24 @@ public class DelegatingIntroductionInterceptorTests extends TestCase {
return t;
}
}
DelegatingIntroductionInterceptor ii = new DelegatingIntroductionInterceptor(new Tester());
TestBean target = new TestBean();
ProxyFactory pf = new ProxyFactory(target);
pf.addAdvisor(0, new DefaultIntroductionAdvisor(ii));
//assertTrue(Arrays.binarySearch(pf.getProxiedInterfaces(), TimeStamped.class) != -1);
TimeStamped ts = (TimeStamped) pf.getProxy();
assertTrue(ts.getTimeStamp() == t);
((ITester) ts).foo();
((ITestBean) ts).getAge();
}
public void testAutomaticInterfaceRecognitionInSubclass() throws Exception {
final long t = 1001L;
class TestII extends DelegatingIntroductionInterceptor implements TimeStamped, ITester {
......@@ -148,28 +148,28 @@ public class DelegatingIntroductionInterceptorTests extends TestCase {
return t;
}
}
DelegatingIntroductionInterceptor ii = new TestII();
TestBean target = new TestBean();
ProxyFactory pf = new ProxyFactory(target);
IntroductionAdvisor ia = new DefaultIntroductionAdvisor(ii);
assertTrue(ia.isPerInstance());
pf.addAdvisor(0, ia);
//assertTrue(Arrays.binarySearch(pf.getProxiedInterfaces(), TimeStamped.class) != -1);
TimeStamped ts = (TimeStamped) pf.getProxy();
assertTrue(ts instanceof TimeStamped);
// Shoulnd't proxy framework interfaces
assertTrue(!(ts instanceof MethodInterceptor));
assertTrue(!(ts instanceof IntroductionInterceptor));
assertTrue(ts.getTimeStamp() == t);
((ITester) ts).foo();
((ITestBean) ts).getAge();
// Test removal
ii.suppressInterface(TimeStamped.class);
// Note that we need to construct a new proxy factory,
......@@ -179,12 +179,12 @@ public class DelegatingIntroductionInterceptorTests extends TestCase {
Object o = pf.getProxy();
assertTrue(!(o instanceof TimeStamped));
}
public void testIntroductionInterceptorDoesntReplaceToString() throws Exception {
TestBean raw = new TestBean();
assertTrue(! (raw instanceof TimeStamped));
ProxyFactory factory = new ProxyFactory(raw);
TimeStamped ts = new SerializableTimeStamped(0);
factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts) {
......@@ -192,55 +192,55 @@ public class DelegatingIntroductionInterceptorTests extends TestCase {
throw new UnsupportedOperationException("Shouldn't be invoked");
}
}));
TimeStamped tsp = (TimeStamped) factory.getProxy();
assertEquals(0, tsp.getTimeStamp());
assertEquals(raw.toString(), tsp.toString());
}
public void testDelegateReturnsThisIsMassagedToReturnProxy() {
NestedTestBean target = new NestedTestBean();
String company = "Interface21";
target.setCompany(company);
TestBean delegate = new TestBean() {
public ITestBean getSpouse() {
return this;
}
};
ProxyFactory pf = new ProxyFactory(target);
pf.addAdvice(new DelegatingIntroductionInterceptor(delegate));
INestedTestBean proxy = (INestedTestBean) pf.getProxy();
assertEquals(company, proxy.getCompany());
ITestBean introduction = (ITestBean) proxy;
assertSame("Introduced method returning delegate returns proxy", introduction, introduction.getSpouse());
assertTrue("Introduced method returning delegate returns proxy", AopUtils.isAopProxy(introduction.getSpouse()));
NestedTestBean target = new NestedTestBean();
String company = "Interface21";
target.setCompany(company);
TestBean delegate = new TestBean() {
public ITestBean getSpouse() {
return this;
}
};
ProxyFactory pf = new ProxyFactory(target);
pf.addAdvice(new DelegatingIntroductionInterceptor(delegate));
INestedTestBean proxy = (INestedTestBean) pf.getProxy();
assertEquals(company, proxy.getCompany());
ITestBean introduction = (ITestBean) proxy;
assertSame("Introduced method returning delegate returns proxy", introduction, introduction.getSpouse());
assertTrue("Introduced method returning delegate returns proxy", AopUtils.isAopProxy(introduction.getSpouse()));
}
public void testSerializableDelegatingIntroductionInterceptorSerializable() throws Exception {
SerializablePerson serializableTarget = new SerializablePerson();
String name = "Tony";
serializableTarget.setName("Tony");
ProxyFactory factory = new ProxyFactory(serializableTarget);
factory.addInterface(Person.class);
long time = 1000;
TimeStamped ts = new SerializableTimeStamped(time);
factory.addAdvisor(new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts)));
factory.addAdvice(new SerializableNopInterceptor());
Person p = (Person) factory.getProxy();
assertEquals(name, p.getName());
assertEquals(time, ((TimeStamped) p).getTimeStamp());
Person p1 = (Person) SerializationTestUtils.serializeAndDeserialize(p);
assertEquals(name, p1.getName());
assertEquals(time, ((TimeStamped) p1).getTimeStamp());
}
// public void testDelegatingIntroductionInterceptorDoesntMakeNonserializableSerializable() throws Exception {
// // Target is NOT serialiable
// TestBean raw = new TestBean();
......@@ -263,15 +263,15 @@ public class DelegatingIntroductionInterceptorTests extends TestCase {
return t;
}
}
DelegatingIntroductionInterceptor ii = new TestII();
// != t
TestBean target = new TargetClass(t + 1);
ProxyFactory pf = new ProxyFactory(target);
pf.addAdvisor(0, new DefaultIntroductionAdvisor(ii));
TimeStamped ts = (TimeStamped) pf.getProxy();
// From introduction interceptor, not target
assertTrue(ts.getTimeStamp() == t);
......
......@@ -23,6 +23,7 @@ package org.springframework.beans.factory;
* @author Rick Evans
*/
class PackageLevelVisibleBean {
public static final String CONSTANT = "Wuby";
public static final String CONSTANT = "Wuby";
}
......@@ -20,56 +20,56 @@ import java.util.List;
/**
* Scrap bean for use in tests.
*
*
* @author Colin Sampaleanu
*/
public class TestBean {
private String name;
private String name;
private List list;
private List list;
private Object objRef;
private Object objRef;
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
/**
* @return Returns the list.
*/
public List getList() {
return list;
}
/**
* @return Returns the list.
*/
public List getList() {
return list;
}
/**
* @param list The list to set.
*/
public void setList(List list) {
this.list = list;
}
/**
* @param list The list to set.
*/
public void setList(List list) {
this.list = list;
}
/**
* @return Returns the object.
*/
public Object getObjRef() {
return objRef;
}
/**
* @return Returns the object.
*/
public Object getObjRef() {
return objRef;
}
/**
* @param object The object to set.
*/
public void setObjRef(Object object) {
this.objRef = object;
}
/**
* @param object The object to set.
*/
public void setObjRef(Object object) {
this.objRef = object;
}
}
......@@ -27,33 +27,33 @@ import org.springframework.test.AssertThrows;
*/
public final class CommonsLogFactoryBeanTests extends TestCase {
public void testIsSingleton() throws Exception {
CommonsLogFactoryBean factory = new CommonsLogFactoryBean();
assertTrue(factory.isSingleton());
}
public void testGetObjectTypeDefaultsToPlainResourceInterfaceifLookupResourceIsNotSupplied() throws Exception {
CommonsLogFactoryBean factory = new CommonsLogFactoryBean();
assertEquals(Log.class, factory.getObjectType());
}
public void testWhenLogNameIsMissing() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
CommonsLogFactoryBean factory = new CommonsLogFactoryBean();
factory.afterPropertiesSet();
}
}.runTest();
}
public void testSunnyDayPath() throws Exception {
CommonsLogFactoryBean factory = new CommonsLogFactoryBean();
factory.setLogName("The Tin Drum");
factory.afterPropertiesSet();
Object object = factory.getObject();
assertNotNull("As per FactoryBean contract, the return value of getObject() cannot be null.", object);
assertTrue("Obviously not getting a Log back", Log.class.isAssignableFrom(object.getClass()));
}
public void testIsSingleton() throws Exception {
CommonsLogFactoryBean factory = new CommonsLogFactoryBean();
assertTrue(factory.isSingleton());
}
public void testGetObjectTypeDefaultsToPlainResourceInterfaceifLookupResourceIsNotSupplied() throws Exception {
CommonsLogFactoryBean factory = new CommonsLogFactoryBean();
assertEquals(Log.class, factory.getObjectType());
}
public void testWhenLogNameIsMissing() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
CommonsLogFactoryBean factory = new CommonsLogFactoryBean();
factory.afterPropertiesSet();
}
}.runTest();
}
public void testSunnyDayPath() throws Exception {
CommonsLogFactoryBean factory = new CommonsLogFactoryBean();
factory.setLogName("The Tin Drum");
factory.afterPropertiesSet();
Object object = factory.getObject();
assertNotNull("As per FactoryBean contract, the return value of getObject() cannot be null.", object);
assertTrue("Obviously not getting a Log back", Log.class.isAssignableFrom(object.getClass()));
}
}
......@@ -48,11 +48,12 @@ import org.springframework.util.StringUtils;
/**
* @author Juergen Hoeller
* @author Chris Beams
* @since 02.10.2003
*/
public class PropertyResourceConfigurerTests {
@Test
@Test
public void testPropertyOverrideConfigurer() {
StaticApplicationContext ac = new StaticApplicationContext();
ac.registerSingleton("tb1", TestBean.class);
......@@ -73,7 +74,7 @@ public class PropertyResourceConfigurerTests {
assertEquals("test", tb2.getName());
}
@Test
@Test
public void testPropertyOverrideConfigurerWithNestedProperty() {
StaticApplicationContext ac = new StaticApplicationContext();
ac.registerSingleton("tb", IndexedTestBean.class);
......@@ -86,7 +87,7 @@ public class PropertyResourceConfigurerTests {
assertEquals("test", ((TestBean) tb.getList().get(1)).getName());
}
@Test
@Test
public void testPropertyOverrideConfigurerWithNestedPropertyAndDotInBeanName() {
StaticApplicationContext ac = new StaticApplicationContext();
ac.registerSingleton("my.tb", IndexedTestBean.class);
......@@ -100,7 +101,7 @@ public class PropertyResourceConfigurerTests {
assertEquals("test", ((TestBean) tb.getList().get(1)).getName());
}
@Test
@Test
public void testPropertyOverrideConfigurerWithNestedMapPropertyAndDotInMapKey() {
StaticApplicationContext ac = new StaticApplicationContext();
ac.registerSingleton("tb", IndexedTestBean.class);
......@@ -113,7 +114,7 @@ public class PropertyResourceConfigurerTests {
assertEquals("test", tb.getMap().get("key2.ext"));
}
@Test
@Test
public void testPropertyOverrideConfigurerWithJavaMailProperties() {
StaticApplicationContext ac = new StaticApplicationContext();
ac.registerSingleton("tb", JavaMailSenderImpl.class);
......@@ -125,7 +126,7 @@ public class PropertyResourceConfigurerTests {
assertEquals("true", tb.getJavaMailProperties().getProperty("mail.smtp.auth"));
}
@Test
@Test
public void testPropertyOverrideConfigurerWithPropertiesFile() {
StaticApplicationContext ac = new StaticApplicationContext();
ac.registerSingleton("tb", IndexedTestBean.class);
......@@ -138,7 +139,7 @@ public class PropertyResourceConfigurerTests {
assertEquals("test", ((TestBean) tb.getList().get(1)).getName());
}
@Test
@Test
public void testPropertyOverrideConfigurerWithInvalidPropertiesFile() {
StaticApplicationContext ac = new StaticApplicationContext();
ac.registerSingleton("tb", IndexedTestBean.class);
......@@ -154,7 +155,7 @@ public class PropertyResourceConfigurerTests {
assertEquals("test", ((TestBean) tb.getList().get(1)).getName());
}
@Test
@Test
public void testPropertyOverrideConfigurerWithPropertiesXmlFile() {
// ignore for JDK < 1.5
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) {
......@@ -172,7 +173,7 @@ public class PropertyResourceConfigurerTests {
assertEquals("test", ((TestBean) tb.getList().get(1)).getName());
}
@Test
@Test
public void testPropertyOverrideConfigurerWithConvertProperties() {
StaticApplicationContext ac = new StaticApplicationContext();
ac.registerSingleton("tb", IndexedTestBean.class);
......@@ -185,7 +186,7 @@ public class PropertyResourceConfigurerTests {
assertEquals("Xtest", ((TestBean) tb.getList().get(1)).getName());
}
@Test
@Test
public void testPropertyOverrideConfigurerWithInvalidKey() {
StaticApplicationContext ac = new StaticApplicationContext();
ac.registerSingleton("tb1", TestBean.class);
......@@ -206,7 +207,7 @@ public class PropertyResourceConfigurerTests {
}
}
@Test
@Test
public void testPropertyOverrideConfigurerWithIgnoreInvalidKeys() {
StaticApplicationContext ac = new StaticApplicationContext();
ac.registerSingleton("tb1", TestBean.class);
......@@ -228,12 +229,12 @@ public class PropertyResourceConfigurerTests {
assertEquals("test", tb2.getName());
}
@Test
@Test
public void testPropertyPlaceholderConfigurer() {
doTestPropertyPlaceholderConfigurer(false);
}
@Test
@Test
public void testPropertyPlaceholderConfigurerWithParentChildSeparation() {
doTestPropertyPlaceholderConfigurer(true);
}
......
......@@ -276,7 +276,7 @@ public class XmlBeanCollectionTests extends TestCase {
XmlBeanFactory xbf = new XmlBeanFactory(new ClassPathResource("collections.xml", getClass()));
HasMap hasMap = (HasMap) xbf.getBean("props");
assertTrue(hasMap.getProps().size() == 2);
assertTrue(hasMap.getProps().get("foo").equals("bar"));
assertTrue(hasMap.getProps().get("foo").equals("bar"));
assertTrue(hasMap.getProps().get("2").equals("TWO"));
}
......
......@@ -23,19 +23,19 @@ package org.springframework.context;
* @since January 21, 2001
*/
public class TestListener implements ApplicationListener {
private int eventCount;
public int getEventCount() {
return eventCount;
}
public void zeroCounter() {
eventCount = 0;
}
public void onApplicationEvent(ApplicationEvent e) {
++eventCount;
}
}
......@@ -38,26 +38,26 @@ import org.springframework.web.context.support.GenericWebApplicationContext;
public class ClassPathBeanDefinitionScannerScopeTests extends TestCase {
private static final String DEFAULT_NAME = "default";
private static final String MODIFIED_NAME = "modified";
private ServletRequestAttributes oldRequestAttributes;
private ServletRequestAttributes newRequestAttributes;
private ServletRequestAttributes oldRequestAttributesWithSession;
private ServletRequestAttributes newRequestAttributesWithSession;
public void setUp() {
this.oldRequestAttributes = new ServletRequestAttributes(new MockHttpServletRequest());
this.newRequestAttributes = new ServletRequestAttributes(new MockHttpServletRequest());
MockHttpServletRequest oldRequestWithSession = new MockHttpServletRequest();
oldRequestWithSession.setSession(new MockHttpSession());
this.oldRequestAttributesWithSession = new ServletRequestAttributes(oldRequestWithSession);
MockHttpServletRequest newRequestWithSession = new MockHttpServletRequest();
newRequestWithSession.setSession(new MockHttpSession());
this.newRequestAttributesWithSession = new ServletRequestAttributes(newRequestWithSession);
......@@ -72,17 +72,17 @@ public class ClassPathBeanDefinitionScannerScopeTests extends TestCase {
RequestContextHolder.setRequestAttributes(oldRequestAttributes);
ApplicationContext context = createContext(ScopedProxyMode.NO);
ScopedTestBean bean = (ScopedTestBean) context.getBean("singleton");
// should not be a proxy
assertFalse(AopUtils.isAopProxy(bean));
assertEquals(DEFAULT_NAME, bean.getName());
bean.setName(MODIFIED_NAME);
RequestContextHolder.setRequestAttributes(newRequestAttributes);
// not a proxy so this should not have changed
assertEquals(MODIFIED_NAME, bean.getName());
// singleton bean, so name should be modified even after lookup
ScopedTestBean bean2 = (ScopedTestBean) context.getBean("singleton");
assertEquals(MODIFIED_NAME, bean2.getName());
......@@ -92,17 +92,17 @@ public class ClassPathBeanDefinitionScannerScopeTests extends TestCase {
RequestContextHolder.setRequestAttributes(oldRequestAttributes);
ApplicationContext context = createContext(ScopedProxyMode.INTERFACES);
ScopedTestBean bean = (ScopedTestBean) context.getBean("singleton");
// should not be a proxy
assertFalse(AopUtils.isAopProxy(bean));
assertEquals(DEFAULT_NAME, bean.getName());
bean.setName(MODIFIED_NAME);
RequestContextHolder.setRequestAttributes(newRequestAttributes);
// not a proxy so this should not have changed
assertEquals(MODIFIED_NAME, bean.getName());
// singleton bean, so name should be modified even after lookup
ScopedTestBean bean2 = (ScopedTestBean) context.getBean("singleton");
assertEquals(MODIFIED_NAME, bean2.getName());
......@@ -112,37 +112,37 @@ public class ClassPathBeanDefinitionScannerScopeTests extends TestCase {
RequestContextHolder.setRequestAttributes(oldRequestAttributes);
ApplicationContext context = createContext(ScopedProxyMode.TARGET_CLASS);
ScopedTestBean bean = (ScopedTestBean) context.getBean("singleton");
// should not be a proxy
assertFalse(AopUtils.isAopProxy(bean));
assertEquals(DEFAULT_NAME, bean.getName());
bean.setName(MODIFIED_NAME);
RequestContextHolder.setRequestAttributes(newRequestAttributes);
// not a proxy so this should not have changed
assertEquals(MODIFIED_NAME, bean.getName());
// singleton bean, so name should be modified even after lookup
ScopedTestBean bean2 = (ScopedTestBean) context.getBean("singleton");
assertEquals(MODIFIED_NAME, bean2.getName());
}
public void testRequestScopeWithNoProxy() {
RequestContextHolder.setRequestAttributes(oldRequestAttributes);
ApplicationContext context = createContext(ScopedProxyMode.NO);
ScopedTestBean bean = (ScopedTestBean) context.getBean("request");
// should not be a proxy
assertFalse(AopUtils.isAopProxy(bean));
assertEquals(DEFAULT_NAME, bean.getName());
bean.setName(MODIFIED_NAME);
RequestContextHolder.setRequestAttributes(newRequestAttributes);
// not a proxy so this should not have changed
assertEquals(MODIFIED_NAME, bean.getName());
// but a newly retrieved bean should have the default name
ScopedTestBean bean2 = (ScopedTestBean) context.getBean("request");
assertEquals(DEFAULT_NAME, bean2.getName());
......@@ -152,18 +152,18 @@ public class ClassPathBeanDefinitionScannerScopeTests extends TestCase {
RequestContextHolder.setRequestAttributes(oldRequestAttributes);
ApplicationContext context = createContext(ScopedProxyMode.INTERFACES);
IScopedTestBean bean = (IScopedTestBean) context.getBean("request");
// should be dynamic proxy, implementing both interfaces
assertTrue(AopUtils.isJdkDynamicProxy(bean));
assertTrue(bean instanceof AnotherScopeTestInterface);
assertEquals(DEFAULT_NAME, bean.getName());
bean.setName(MODIFIED_NAME);
RequestContextHolder.setRequestAttributes(newRequestAttributes);
// this is a proxy so it should be reset to default
assertEquals(DEFAULT_NAME, bean.getName());
RequestContextHolder.setRequestAttributes(oldRequestAttributes);
assertEquals(MODIFIED_NAME, bean.getName());
}
......@@ -172,22 +172,22 @@ public class ClassPathBeanDefinitionScannerScopeTests extends TestCase {
RequestContextHolder.setRequestAttributes(oldRequestAttributes);
ApplicationContext context = createContext(ScopedProxyMode.TARGET_CLASS);
IScopedTestBean bean = (IScopedTestBean) context.getBean("request");
// should be a class-based proxy
assertTrue(AopUtils.isCglibProxy(bean));
assertTrue(bean instanceof RequestScopedTestBean);
assertEquals(DEFAULT_NAME, bean.getName());
bean.setName(MODIFIED_NAME);
RequestContextHolder.setRequestAttributes(newRequestAttributes);
// this is a proxy so it should be reset to default
assertEquals(DEFAULT_NAME, bean.getName());
RequestContextHolder.setRequestAttributes(oldRequestAttributes);
assertEquals(MODIFIED_NAME, bean.getName());
}
public void testSessionScopeWithNoProxy() {
RequestContextHolder.setRequestAttributes(oldRequestAttributesWithSession);
ApplicationContext context = createContext(ScopedProxyMode.NO);
......@@ -195,14 +195,14 @@ public class ClassPathBeanDefinitionScannerScopeTests extends TestCase {
// should not be a proxy
assertFalse(AopUtils.isAopProxy(bean));
assertEquals(DEFAULT_NAME, bean.getName());
bean.setName(MODIFIED_NAME);
RequestContextHolder.setRequestAttributes(newRequestAttributesWithSession);
// not a proxy so this should not have changed
assertEquals(MODIFIED_NAME, bean.getName());
// but a newly retrieved bean should have the default name
ScopedTestBean bean2 = (ScopedTestBean) context.getBean("session");
assertEquals(DEFAULT_NAME, bean2.getName());
......@@ -212,24 +212,24 @@ public class ClassPathBeanDefinitionScannerScopeTests extends TestCase {
RequestContextHolder.setRequestAttributes(oldRequestAttributesWithSession);
ApplicationContext context = createContext(ScopedProxyMode.INTERFACES);
IScopedTestBean bean = (IScopedTestBean) context.getBean("session");
// should be dynamic proxy, implementing both interfaces
assertTrue(AopUtils.isJdkDynamicProxy(bean));
assertTrue(bean instanceof AnotherScopeTestInterface);
assertEquals(DEFAULT_NAME, bean.getName());
bean.setName(MODIFIED_NAME);
RequestContextHolder.setRequestAttributes(newRequestAttributesWithSession);
// this is a proxy so it should be reset to default
assertEquals(DEFAULT_NAME, bean.getName());
bean.setName(MODIFIED_NAME);
IScopedTestBean bean2 = (IScopedTestBean) context.getBean("session");
assertEquals(MODIFIED_NAME, bean2.getName());
bean2.setName(DEFAULT_NAME);
assertEquals(DEFAULT_NAME, bean.getName());
RequestContextHolder.setRequestAttributes(oldRequestAttributesWithSession);
assertEquals(MODIFIED_NAME, bean.getName());
}
......@@ -284,8 +284,8 @@ public class ClassPathBeanDefinitionScannerScopeTests extends TestCase {
context.refresh();
return context;
}
public static @interface ScopeTestComponent {
}
......@@ -296,7 +296,7 @@ public class ClassPathBeanDefinitionScannerScopeTests extends TestCase {
void setName(String name);
}
public static abstract class ScopedTestBean implements IScopedTestBean {
......@@ -306,16 +306,16 @@ public class ClassPathBeanDefinitionScannerScopeTests extends TestCase {
public void setName(String name) { this.name = name; }
}
@ScopeTestComponent
public static class SingletonScopedTestBean extends ScopedTestBean {
}
public static interface AnotherScopeTestInterface {
}
@Scope("request")
@ScopeTestComponent
......
......@@ -1096,8 +1096,8 @@ public class BridgeMethodResolverTests {
public class BusinessDao extends BusinessGenericDao<Business<?>, Long> {
public void save(Business<?> business) {
}
public void save(Business<?> business) {
}
public Business<?> get(Long id) {
return null;
......
......@@ -40,7 +40,7 @@ import org.springframework.web.context.support.ServletContextResource;
*/
public class ResourceTests {
@Test
@Test
public void testByteArrayResource() throws IOException {
Resource resource = new ByteArrayResource("testString".getBytes());
assertTrue(resource.exists());
......@@ -49,8 +49,8 @@ public class ResourceTests {
assertEquals("testString", content);
assertEquals(resource, new ByteArrayResource("testString".getBytes()));
}
@Test
@Test
public void testByteArrayResourceWithDescription() throws IOException {
Resource resource = new ByteArrayResource("testString".getBytes(), "my description");
assertTrue(resource.exists());
......@@ -61,7 +61,7 @@ public class ResourceTests {
assertEquals(resource, new ByteArrayResource("testString".getBytes()));
}
@Test
@Test
public void testInputStreamResource() throws IOException {
InputStream is = new ByteArrayInputStream("testString".getBytes());
Resource resource = new InputStreamResource(is);
......@@ -72,7 +72,7 @@ public class ResourceTests {
assertEquals(resource, new InputStreamResource(is));
}
@Test
@Test
public void testInputStreamResourceWithDescription() throws IOException {
InputStream is = new ByteArrayInputStream("testString".getBytes());
Resource resource = new InputStreamResource(is, "my description");
......@@ -84,7 +84,7 @@ public class ResourceTests {
assertEquals(resource, new InputStreamResource(is));
}
@Test
@Test
public void testClassPathResource() throws IOException {
Resource resource = new ClassPathResource("org/springframework/core/io/Resource.class");
doTestResource(resource);
......@@ -100,7 +100,7 @@ public class ResourceTests {
assertEquals(1, resources.size());
}
@Test
@Test
public void testClassPathResourceWithClassLoader() throws IOException {
Resource resource =
new ClassPathResource("org/springframework/core/io/Resource.class", getClass().getClassLoader());
......@@ -109,15 +109,15 @@ public class ResourceTests {
new ClassPathResource("org/springframework/core/../core/io/./Resource.class", getClass().getClassLoader()));
}
@Test
@Test
public void testClassPathResourceWithClass() throws IOException {
Resource resource = new ClassPathResource("Resource.class", getClass());
doTestResource(resource);
assertEquals(resource, new ClassPathResource("Resource.class", getClass()));
}
@Ignore // passes under eclipse, fails under ant
@Test
@Ignore // passes under eclipse, fails under ant
@Test
public void testFileSystemResource() throws IOException {
Resource resource = new FileSystemResource(getClass().getResource("Resource.class").getFile());
doTestResource(resource);
......@@ -126,7 +126,7 @@ public class ResourceTests {
assertEquals(resource2, new FileSystemResource("core/../core/io/./Resource.class"));
}
@Test
@Test
public void testUrlResource() throws IOException {
Resource resource = new UrlResource(getClass().getResource("Resource.class"));
doTestResource(resource);
......@@ -135,7 +135,7 @@ public class ResourceTests {
assertEquals(resource2, new UrlResource("file:core/../core/io/./Resource.class"));
}
@Test
@Test
public void testServletContextResource() throws IOException {
MockServletContext sc = new MockServletContext();
Resource resource = new ServletContextResource(sc, "org/springframework/core/io/Resource.class");
......
......@@ -28,45 +28,45 @@ import javax.jms.Session;
*/
public final class JmsAccessorTests extends TestCase {
public void testChokesIfConnectionFactoryIsNotSupplied() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
JmsAccessor accessor = new StubJmsAccessor();
accessor.afterPropertiesSet();
}
}.runTest();
}
public void testChokesIfConnectionFactoryIsNotSupplied() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
JmsAccessor accessor = new StubJmsAccessor();
accessor.afterPropertiesSet();
}
}.runTest();
}
public void testSessionTransactedModeReallyDoesDefaultToFalse() throws Exception {
JmsAccessor accessor = new StubJmsAccessor();
assertFalse("The [sessionTransacted] property of JmsAccessor must default to " +
"false. Change this test (and the attendant Javadoc) if you have " +
"changed the default.",
accessor.isSessionTransacted());
}
public void testSessionTransactedModeReallyDoesDefaultToFalse() throws Exception {
JmsAccessor accessor = new StubJmsAccessor();
assertFalse("The [sessionTransacted] property of JmsAccessor must default to " +
"false. Change this test (and the attendant Javadoc) if you have " +
"changed the default.",
accessor.isSessionTransacted());
}
public void testAcknowledgeModeReallyDoesDefaultToAutoAcknowledge() throws Exception {
JmsAccessor accessor = new StubJmsAccessor();
assertEquals("The [sessionAcknowledgeMode] property of JmsAccessor must default to " +
"[Session.AUTO_ACKNOWLEDGE]. Change this test (and the attendant " +
"Javadoc) if you have changed the default.",
Session.AUTO_ACKNOWLEDGE,
accessor.getSessionAcknowledgeMode());
}
public void testAcknowledgeModeReallyDoesDefaultToAutoAcknowledge() throws Exception {
JmsAccessor accessor = new StubJmsAccessor();
assertEquals("The [sessionAcknowledgeMode] property of JmsAccessor must default to " +
"[Session.AUTO_ACKNOWLEDGE]. Change this test (and the attendant " +
"Javadoc) if you have changed the default.",
Session.AUTO_ACKNOWLEDGE,
accessor.getSessionAcknowledgeMode());
}
public void testSetAcknowledgeModeNameChokesIfBadAckModeIsSupplied() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
new StubJmsAccessor().setSessionAcknowledgeModeName("Tally ho chaps!");
}
}.runTest();
}
public void testSetAcknowledgeModeNameChokesIfBadAckModeIsSupplied() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
new StubJmsAccessor().setSessionAcknowledgeModeName("Tally ho chaps!");
}
}.runTest();
}
/**
* Crummy, stub, do-nothing subclass of the JmsAccessor class for use in testing.
*/
private static final class StubJmsAccessor extends JmsAccessor {
}
/**
* Crummy, stub, do-nothing subclass of the JmsAccessor class for use in testing.
*/
private static final class StubJmsAccessor extends JmsAccessor {
}
}
......@@ -35,42 +35,42 @@ import java.util.Arrays;
*/
public final class SimpleMessageConverter102Tests extends TestCase {
public void testByteArrayConversion102() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(BytesMessage.class);
BytesMessage message = (BytesMessage) messageControl.getMock();
public void testByteArrayConversion102() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(BytesMessage.class);
BytesMessage message = (BytesMessage) messageControl.getMock();
byte[] content = new byte[5000];
byte[] content = new byte[5000];
session.createBytesMessage();
sessionControl.setReturnValue(message, 1);
message.writeBytes(content);
messageControl.setVoidCallable(1);
message.readBytes(new byte[SimpleMessageConverter102.BUFFER_SIZE]);
messageControl.setMatcher(new ArgumentsMatcher() {
public boolean matches(Object[] arg0, Object[] arg1) {
byte[] one = (byte[]) arg0[0];
byte[] two = (byte[]) arg1[0];
return Arrays.equals(one, two);
}
session.createBytesMessage();
sessionControl.setReturnValue(message, 1);
message.writeBytes(content);
messageControl.setVoidCallable(1);
message.readBytes(new byte[SimpleMessageConverter102.BUFFER_SIZE]);
messageControl.setMatcher(new ArgumentsMatcher() {
public boolean matches(Object[] arg0, Object[] arg1) {
byte[] one = (byte[]) arg0[0];
byte[] two = (byte[]) arg1[0];
return Arrays.equals(one, two);
}
public String toString(Object[] arg0) {
return "bla";
}
});
messageControl.setReturnValue(SimpleMessageConverter102.BUFFER_SIZE, 1);
message.readBytes(new byte[SimpleMessageConverter102.BUFFER_SIZE]);
messageControl.setReturnValue(5000 - SimpleMessageConverter102.BUFFER_SIZE, 1);
sessionControl.replay();
messageControl.replay();
public String toString(Object[] arg0) {
return "bla";
}
});
messageControl.setReturnValue(SimpleMessageConverter102.BUFFER_SIZE, 1);
message.readBytes(new byte[SimpleMessageConverter102.BUFFER_SIZE]);
messageControl.setReturnValue(5000 - SimpleMessageConverter102.BUFFER_SIZE, 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter102 converter = new SimpleMessageConverter102();
Message msg = converter.toMessage(content, session);
assertEquals(content.length, ((byte[]) converter.fromMessage(msg)).length);
SimpleMessageConverter102 converter = new SimpleMessageConverter102();
Message msg = converter.toMessage(content, session);
assertEquals(content.length, ((byte[]) converter.fromMessage(msg)).length);
sessionControl.verify();
messageControl.verify();
}
sessionControl.verify();
messageControl.verify();
}
}
......@@ -38,222 +38,222 @@ import java.util.Map;
*/
public final class SimpleMessageConverterTests extends TestCase {
public void testStringConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(TextMessage.class);
TextMessage message = (TextMessage) messageControl.getMock();
String content = "test";
session.createTextMessage(content);
sessionControl.setReturnValue(message, 1);
message.getText();
messageControl.setReturnValue(content, 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content, converter.fromMessage(msg));
sessionControl.verify();
messageControl.verify();
}
public void testByteArrayConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(BytesMessage.class);
BytesMessage message = (BytesMessage) messageControl.getMock();
byte[] content = "test".getBytes();
session.createBytesMessage();
sessionControl.setReturnValue(message, 1);
message.writeBytes(content);
messageControl.setVoidCallable(1);
message.getBodyLength();
messageControl.setReturnValue(content.length, 1);
message.readBytes(new byte[content.length]);
messageControl.setMatcher(new ArgumentsMatcher() {
public boolean matches(Object[] arg0, Object[] arg1) {
byte[] one = (byte[]) arg0[0];
byte[] two = (byte[]) arg1[0];
return Arrays.equals(one, two);
}
public String toString(Object[] arg0) {
return "bla";
}
});
messageControl.setReturnValue(content.length, 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content.length, ((byte[]) converter.fromMessage(msg)).length);
sessionControl.verify();
messageControl.verify();
}
public void testMapConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(MapMessage.class);
MapMessage message = (MapMessage) messageControl.getMock();
Map content = new HashMap();
content.put("key1", "value1");
content.put("key2", "value2");
session.createMapMessage();
sessionControl.setReturnValue(message, 1);
message.setObject("key1", "value1");
messageControl.setVoidCallable(1);
message.setObject("key2", "value2");
messageControl.setVoidCallable(1);
message.getMapNames();
messageControl.setReturnValue(Collections.enumeration(content.keySet()));
message.getObject("key1");
messageControl.setReturnValue("value1", 1);
message.getObject("key2");
messageControl.setReturnValue("value2", 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content, converter.fromMessage(msg));
sessionControl.verify();
messageControl.verify();
}
public void testSerializableConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(ObjectMessage.class);
ObjectMessage message = (ObjectMessage) messageControl.getMock();
Integer content = new Integer(5);
session.createObjectMessage(content);
sessionControl.setReturnValue(message, 1);
message.getObject();
messageControl.setReturnValue(content, 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content, converter.fromMessage(msg));
sessionControl.verify();
messageControl.verify();
}
public void testToMessageThrowsExceptionIfGivenNullObjectToConvert() throws Exception {
new AssertThrows(MessageConversionException.class) {
public void test() throws Exception {
new SimpleMessageConverter().toMessage(null, null);
}
}.runTest();
}
public void testToMessageThrowsExceptionIfGivenIncompatibleObjectToConvert() throws Exception {
new AssertThrows(MessageConversionException.class) {
public void test() throws Exception {
new SimpleMessageConverter().toMessage(new Object(), null);
}
}.runTest();
}
public void testToMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(ObjectMessage.class);
ObjectMessage message = (ObjectMessage) messageControl.getMock();
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(message, session);
assertSame(message, msg);
sessionControl.verify();
messageControl.verify();
}
public void testFromMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException {
MockControl messageControl = MockControl.createControl(Message.class);
Message message = (Message) messageControl.getMock();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Object msg = converter.fromMessage(message);
assertSame(message, msg);
messageControl.verify();
}
public void testMapConversionWhereMapHasNonStringTypesForKeys() throws JMSException {
MockControl messageControl = MockControl.createControl(MapMessage.class);
MapMessage message = (MapMessage) messageControl.getMock();
messageControl.replay();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
session.createMapMessage();
sessionControl.setReturnValue(message);
sessionControl.replay();
final Map content = new HashMap();
content.put(new Integer(1), "value1");
public void testStringConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(TextMessage.class);
TextMessage message = (TextMessage) messageControl.getMock();
String content = "test";
session.createTextMessage(content);
sessionControl.setReturnValue(message, 1);
message.getText();
messageControl.setReturnValue(content, 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content, converter.fromMessage(msg));
sessionControl.verify();
messageControl.verify();
}
public void testByteArrayConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(BytesMessage.class);
BytesMessage message = (BytesMessage) messageControl.getMock();
byte[] content = "test".getBytes();
session.createBytesMessage();
sessionControl.setReturnValue(message, 1);
message.writeBytes(content);
messageControl.setVoidCallable(1);
message.getBodyLength();
messageControl.setReturnValue(content.length, 1);
message.readBytes(new byte[content.length]);
messageControl.setMatcher(new ArgumentsMatcher() {
public boolean matches(Object[] arg0, Object[] arg1) {
byte[] one = (byte[]) arg0[0];
byte[] two = (byte[]) arg1[0];
return Arrays.equals(one, two);
}
public String toString(Object[] arg0) {
return "bla";
}
});
messageControl.setReturnValue(content.length, 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content.length, ((byte[]) converter.fromMessage(msg)).length);
sessionControl.verify();
messageControl.verify();
}
public void testMapConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(MapMessage.class);
MapMessage message = (MapMessage) messageControl.getMock();
Map content = new HashMap();
content.put("key1", "value1");
content.put("key2", "value2");
session.createMapMessage();
sessionControl.setReturnValue(message, 1);
message.setObject("key1", "value1");
messageControl.setVoidCallable(1);
message.setObject("key2", "value2");
messageControl.setVoidCallable(1);
message.getMapNames();
messageControl.setReturnValue(Collections.enumeration(content.keySet()));
message.getObject("key1");
messageControl.setReturnValue("value1", 1);
message.getObject("key2");
messageControl.setReturnValue("value2", 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content, converter.fromMessage(msg));
sessionControl.verify();
messageControl.verify();
}
public void testSerializableConversion() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(ObjectMessage.class);
ObjectMessage message = (ObjectMessage) messageControl.getMock();
Integer content = new Integer(5);
session.createObjectMessage(content);
sessionControl.setReturnValue(message, 1);
message.getObject();
messageControl.setReturnValue(content, 1);
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(content, session);
assertEquals(content, converter.fromMessage(msg));
sessionControl.verify();
messageControl.verify();
}
public void testToMessageThrowsExceptionIfGivenNullObjectToConvert() throws Exception {
new AssertThrows(MessageConversionException.class) {
public void test() throws Exception {
new SimpleMessageConverter().toMessage(null, null);
}
}.runTest();
}
public void testToMessageThrowsExceptionIfGivenIncompatibleObjectToConvert() throws Exception {
new AssertThrows(MessageConversionException.class) {
public void test() throws Exception {
new SimpleMessageConverter().toMessage(new Object(), null);
}
}.runTest();
}
public void testToMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException {
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl messageControl = MockControl.createControl(ObjectMessage.class);
ObjectMessage message = (ObjectMessage) messageControl.getMock();
sessionControl.replay();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Message msg = converter.toMessage(message, session);
assertSame(message, msg);
sessionControl.verify();
messageControl.verify();
}
public void testFromMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException {
MockControl messageControl = MockControl.createControl(Message.class);
Message message = (Message) messageControl.getMock();
messageControl.replay();
SimpleMessageConverter converter = new SimpleMessageConverter();
Object msg = converter.fromMessage(message);
assertSame(message, msg);
messageControl.verify();
}
public void testMapConversionWhereMapHasNonStringTypesForKeys() throws JMSException {
MockControl messageControl = MockControl.createControl(MapMessage.class);
MapMessage message = (MapMessage) messageControl.getMock();
messageControl.replay();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
session.createMapMessage();
sessionControl.setReturnValue(message);
sessionControl.replay();
final Map content = new HashMap();
content.put(new Integer(1), "value1");
final SimpleMessageConverter converter = new SimpleMessageConverter();
new AssertThrows(MessageConversionException.class) {
public void test() throws Exception {
converter.toMessage(content, session);
}
}.runTest();
sessionControl.verify();
}
public void testMapConversionWhereMapHasNNullForKey() throws JMSException {
final SimpleMessageConverter converter = new SimpleMessageConverter();
new AssertThrows(MessageConversionException.class) {
public void test() throws Exception {
converter.toMessage(content, session);
}
}.runTest();
sessionControl.verify();
}
public void testMapConversionWhereMapHasNNullForKey() throws JMSException {
MockControl messageControl = MockControl.createControl(MapMessage.class);
MapMessage message = (MapMessage) messageControl.getMock();
messageControl.replay();
MockControl messageControl = MockControl.createControl(MapMessage.class);
MapMessage message = (MapMessage) messageControl.getMock();
messageControl.replay();
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
session.createMapMessage();
sessionControl.setReturnValue(message);
sessionControl.replay();
final Map content = new HashMap();
content.put(null, "value1");
MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
session.createMapMessage();
sessionControl.setReturnValue(message);
sessionControl.replay();
final Map content = new HashMap();
content.put(null, "value1");
final SimpleMessageConverter converter = new SimpleMessageConverter();
new AssertThrows(MessageConversionException.class) {
public void test() throws Exception {
converter.toMessage(content, session);
}
}.runTest();
final SimpleMessageConverter converter = new SimpleMessageConverter();
new AssertThrows(MessageConversionException.class) {
public void test() throws Exception {
converter.toMessage(content, session);
}
}.runTest();
sessionControl.verify();
}
sessionControl.verify();
}
}
......@@ -35,8 +35,8 @@ import org.springframework.transaction.support.TransactionSynchronizationManager
* @author Juergen Hoeller
*/
public class SharedEntityManagerFactoryTests {
@Test
@Test
public void testValidUsage() {
Object o = new Object();
......
......@@ -36,7 +36,7 @@ import edu.emory.mathcs.backport.java.util.concurrent.ThreadFactory;
*/
public class ScheduledExecutorFactoryBeanTests {
@Test
@Test
public void testThrowsExceptionIfPoolSizeIsLessThanZero() throws Exception {
try {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
......@@ -51,7 +51,7 @@ public class ScheduledExecutorFactoryBeanTests {
}
}
@Test
@Test
public void testShutdownNowIsPropagatedToTheExecutorOnDestroy() throws Exception {
MockControl mockScheduledExecutorService = MockControl.createNiceControl(ScheduledExecutorService.class);
final ScheduledExecutorService executor = (ScheduledExecutorService) mockScheduledExecutorService.getMock();
......@@ -73,7 +73,7 @@ public class ScheduledExecutorFactoryBeanTests {
mockScheduledExecutorService.verify();
}
@Test
@Test
public void testShutdownIsPropagatedToTheExecutorOnDestroy() throws Exception {
MockControl mockScheduledExecutorService = MockControl.createNiceControl(ScheduledExecutorService.class);
final ScheduledExecutorService executor = (ScheduledExecutorService) mockScheduledExecutorService.getMock();
......@@ -96,7 +96,7 @@ public class ScheduledExecutorFactoryBeanTests {
mockScheduledExecutorService.verify();
}
@Test
@Test
public void testOneTimeExecutionIsSetUpAndFiresCorrectly() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
......@@ -115,7 +115,7 @@ public class ScheduledExecutorFactoryBeanTests {
mockRunnable.verify();
}
@Test
@Test
public void testFixedRepeatedExecutionIsSetUpAndFiresCorrectly() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
......@@ -138,7 +138,7 @@ public class ScheduledExecutorFactoryBeanTests {
mockRunnable.verify();
}
@Test
@Test
public void testFixedRepeatedExecutionIsSetUpAndFiresCorrectlyAfterException() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
......@@ -162,8 +162,8 @@ public class ScheduledExecutorFactoryBeanTests {
mockRunnable.verify();
}
@Ignore
@Test
@Ignore
@Test
public void testWithInitialDelayRepeatedExecutionIsSetUpAndFiresCorrectly() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
......@@ -192,8 +192,8 @@ public class ScheduledExecutorFactoryBeanTests {
}
}
@Ignore
@Test
@Ignore
@Test
public void testWithInitialDelayRepeatedExecutionIsSetUpAndFiresCorrectlyAfterException() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
......@@ -223,7 +223,7 @@ public class ScheduledExecutorFactoryBeanTests {
}
}
@Test
@Test
public void testSettingThreadFactoryToNullForcesUseOfDefaultButIsOtherwiseCool() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
......@@ -239,7 +239,7 @@ public class ScheduledExecutorFactoryBeanTests {
factory.destroy();
}
@Test
@Test
public void testSettingRejectedExecutionHandlerToNullForcesUseOfDefaultButIsOtherwiseCool() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
......@@ -255,7 +255,7 @@ public class ScheduledExecutorFactoryBeanTests {
factory.destroy();
}
@Test
@Test
public void testObjectTypeReportsCorrectType() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
assertEquals(ScheduledExecutorService.class, factory.getObjectType());
......
......@@ -37,7 +37,7 @@ import org.springframework.core.task.NoOpRunnable;
*/
public class ScheduledExecutorFactoryBeanTests {
@Test
@Test
public void testThrowsExceptionIfPoolSizeIsLessThanZero() throws Exception {
try {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
......@@ -52,7 +52,7 @@ public class ScheduledExecutorFactoryBeanTests {
}
}
@Test
@Test
public void testShutdownNowIsPropagatedToTheExecutorOnDestroy() throws Exception {
MockControl mockScheduledExecutorService = MockControl.createNiceControl(ScheduledExecutorService.class);
final ScheduledExecutorService executor = (ScheduledExecutorService) mockScheduledExecutorService.getMock();
......@@ -74,7 +74,7 @@ public class ScheduledExecutorFactoryBeanTests {
mockScheduledExecutorService.verify();
}
@Test
@Test
public void testShutdownIsPropagatedToTheExecutorOnDestroy() throws Exception {
MockControl mockScheduledExecutorService = MockControl.createNiceControl(ScheduledExecutorService.class);
final ScheduledExecutorService executor = (ScheduledExecutorService) mockScheduledExecutorService.getMock();
......@@ -97,7 +97,7 @@ public class ScheduledExecutorFactoryBeanTests {
mockScheduledExecutorService.verify();
}
@Test
@Test
public void testOneTimeExecutionIsSetUpAndFiresCorrectly() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
......@@ -116,7 +116,7 @@ public class ScheduledExecutorFactoryBeanTests {
mockRunnable.verify();
}
@Test
@Test
public void testFixedRepeatedExecutionIsSetUpAndFiresCorrectly() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
......@@ -139,7 +139,7 @@ public class ScheduledExecutorFactoryBeanTests {
mockRunnable.verify();
}
@Test
@Test
public void testFixedRepeatedExecutionIsSetUpAndFiresCorrectlyAfterException() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
......@@ -163,8 +163,8 @@ public class ScheduledExecutorFactoryBeanTests {
mockRunnable.verify();
}
@Ignore
@Test
@Ignore
@Test
public void testWithInitialDelayRepeatedExecutionIsSetUpAndFiresCorrectly() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
......@@ -193,8 +193,8 @@ public class ScheduledExecutorFactoryBeanTests {
}
}
@Ignore
@Test
@Ignore
@Test
public void testWithInitialDelayRepeatedExecutionIsSetUpAndFiresCorrectlyAfterException() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
......@@ -224,7 +224,7 @@ public class ScheduledExecutorFactoryBeanTests {
}
}
@Test
@Test
public void testSettingThreadFactoryToNullForcesUseOfDefaultButIsOtherwiseCool() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
......@@ -240,7 +240,7 @@ public class ScheduledExecutorFactoryBeanTests {
factory.destroy();
}
@Test
@Test
public void testSettingRejectedExecutionHandlerToNullForcesUseOfDefaultButIsOtherwiseCool() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
......@@ -256,7 +256,7 @@ public class ScheduledExecutorFactoryBeanTests {
factory.destroy();
}
@Test
@Test
public void testObjectTypeReportsCorrectType() throws Exception {
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
assertEquals(ScheduledExecutorService.class, factory.getObjectType());
......
......@@ -28,162 +28,162 @@ import java.util.Timer;
*/
public final class TimerTaskExecutorTests extends TestCase {
public void testExecuteChokesWithNullTimer() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
TimerTaskExecutor executor = new TimerTaskExecutor();
executor.execute(new NoOpRunnable());
}
}.runTest();
}
public void testExecuteChokesWithNullTask() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
TimerTaskExecutor executor = new TimerTaskExecutor(new Timer());
executor.execute(null);
}
}.runTest();
}
public void testExecuteChokesWithNegativeDelay() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
TimerTaskExecutor executor = new TimerTaskExecutor(new Timer());
executor.setDelay(-10);
executor.execute(new NoOpRunnable());
}
}.runTest();
}
public void testExecuteReallyDoesScheduleTheSuppliedTask() throws Exception {
final Object monitor = new Object();
RunAwareRunnable task = new RunAwareRunnable(monitor);
TimerTaskExecutor executor = new TimerTaskExecutor(new Timer());
executor.execute(task);
synchronized (monitor) {
monitor.wait(5000);
}
assertTrue("Supplied task (a Runnable) is not being invoked.", task.isRunWasCalled());
}
public void testCtorWithNullTimer() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
new TimerTaskExecutor(null);
}
}.runTest();
}
public void testCreateTimerMethodIsCalledIfNoTimerIsExplicitlySupplied() throws Exception {
CreationAwareTimerTaskExecutor executor = new CreationAwareTimerTaskExecutor();
executor.afterPropertiesSet();
assertTrue("If no Timer is set explicitly, then the protected createTimer() " +
"method must be called to create the Timer (it obviously isn't being called).",
executor.isCreateTimerWasCalled());
}
public void testCreateTimerMethodIsNotCalledIfTimerIsExplicitlySupplied() throws Exception {
CreationAwareTimerTaskExecutor executor = new CreationAwareTimerTaskExecutor();
executor.setTimer(new Timer());
executor.afterPropertiesSet();
assertFalse("If a Timer is set explicitly, then the protected createTimer() " +
"method must not be called to create the Timer (it obviously is being called, in error).",
executor.isCreateTimerWasCalled());
}
public void testThatTheDestroyCallbackCancelsTheTimerIfNoTimerIsExplicitlySupplied() throws Exception {
final CancelAwareTimer timer = new CancelAwareTimer();
TimerTaskExecutor executor = new TimerTaskExecutor() {
protected Timer createTimer() {
return timer;
}
};
executor.afterPropertiesSet();
executor.destroy();
assertTrue("When the Timer used is created by the TimerTaskExecutor because " +
"no Timer was set explicitly, then the destroy() callback must cancel() said Timer (it obviously isn't doing this).",
timer.isCancelWasCalled());
}
public void testThatTheDestroyCallbackDoesNotCancelTheTimerIfTheTimerWasSuppliedExplictly() throws Exception {
TimerTaskExecutor executor = new TimerTaskExecutor();
CancelAwareTimer timer = new CancelAwareTimer();
executor.setTimer(timer);
executor.afterPropertiesSet();
executor.destroy();
assertFalse("When the Timer used is not created by the TimerTaskExecutor because " +
"it Timer was set explicitly, then the destroy() callback must NOT cancel() said Timer (it obviously is, in error).",
timer.isCancelWasCalled());
}
private final static class CreationAwareTimerTaskExecutor extends TimerTaskExecutor {
private boolean createTimerWasCalled = false;
public boolean isCreateTimerWasCalled() {
return this.createTimerWasCalled;
}
protected Timer createTimer() {
this.createTimerWasCalled = true;
return super.createTimer();
}
}
private static class CancelAwareTimer extends Timer {
public void testExecuteChokesWithNullTimer() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
TimerTaskExecutor executor = new TimerTaskExecutor();
executor.execute(new NoOpRunnable());
}
}.runTest();
}
public void testExecuteChokesWithNullTask() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
TimerTaskExecutor executor = new TimerTaskExecutor(new Timer());
executor.execute(null);
}
}.runTest();
}
public void testExecuteChokesWithNegativeDelay() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
TimerTaskExecutor executor = new TimerTaskExecutor(new Timer());
executor.setDelay(-10);
executor.execute(new NoOpRunnable());
}
}.runTest();
}
public void testExecuteReallyDoesScheduleTheSuppliedTask() throws Exception {
final Object monitor = new Object();
RunAwareRunnable task = new RunAwareRunnable(monitor);
TimerTaskExecutor executor = new TimerTaskExecutor(new Timer());
executor.execute(task);
synchronized (monitor) {
monitor.wait(5000);
}
assertTrue("Supplied task (a Runnable) is not being invoked.", task.isRunWasCalled());
}
public void testCtorWithNullTimer() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
new TimerTaskExecutor(null);
}
}.runTest();
}
public void testCreateTimerMethodIsCalledIfNoTimerIsExplicitlySupplied() throws Exception {
CreationAwareTimerTaskExecutor executor = new CreationAwareTimerTaskExecutor();
executor.afterPropertiesSet();
assertTrue("If no Timer is set explicitly, then the protected createTimer() " +
"method must be called to create the Timer (it obviously isn't being called).",
executor.isCreateTimerWasCalled());
}
public void testCreateTimerMethodIsNotCalledIfTimerIsExplicitlySupplied() throws Exception {
CreationAwareTimerTaskExecutor executor = new CreationAwareTimerTaskExecutor();
executor.setTimer(new Timer());
executor.afterPropertiesSet();
assertFalse("If a Timer is set explicitly, then the protected createTimer() " +
"method must not be called to create the Timer (it obviously is being called, in error).",
executor.isCreateTimerWasCalled());
}
public void testThatTheDestroyCallbackCancelsTheTimerIfNoTimerIsExplicitlySupplied() throws Exception {
final CancelAwareTimer timer = new CancelAwareTimer();
TimerTaskExecutor executor = new TimerTaskExecutor() {
protected Timer createTimer() {
return timer;
}
};
executor.afterPropertiesSet();
executor.destroy();
assertTrue("When the Timer used is created by the TimerTaskExecutor because " +
"no Timer was set explicitly, then the destroy() callback must cancel() said Timer (it obviously isn't doing this).",
timer.isCancelWasCalled());
}
public void testThatTheDestroyCallbackDoesNotCancelTheTimerIfTheTimerWasSuppliedExplictly() throws Exception {
TimerTaskExecutor executor = new TimerTaskExecutor();
CancelAwareTimer timer = new CancelAwareTimer();
executor.setTimer(timer);
executor.afterPropertiesSet();
executor.destroy();
assertFalse("When the Timer used is not created by the TimerTaskExecutor because " +
"it Timer was set explicitly, then the destroy() callback must NOT cancel() said Timer (it obviously is, in error).",
timer.isCancelWasCalled());
}
private final static class CreationAwareTimerTaskExecutor extends TimerTaskExecutor {
private boolean createTimerWasCalled = false;
public boolean isCreateTimerWasCalled() {
return this.createTimerWasCalled;
}
protected Timer createTimer() {
this.createTimerWasCalled = true;
return super.createTimer();
}
}
private static class CancelAwareTimer extends Timer {
private boolean cancelWasCalled;
private boolean cancelWasCalled;
public boolean isCancelWasCalled() {
return this.cancelWasCalled;
}
public boolean isCancelWasCalled() {
return this.cancelWasCalled;
}
public void cancel() {
this.cancelWasCalled = true;
super.cancel();
}
}
public void cancel() {
this.cancelWasCalled = true;
super.cancel();
}
}
private static class RunAwareRunnable implements Runnable {
private boolean runWasCalled;
private final Object monitor;
private static class RunAwareRunnable implements Runnable {
private boolean runWasCalled;
private final Object monitor;
public RunAwareRunnable(Object monitor) {
this.monitor = monitor;
}
public RunAwareRunnable(Object monitor) {
this.monitor = monitor;
}
public boolean isRunWasCalled() {
return this.runWasCalled;
}
public boolean isRunWasCalled() {
return this.runWasCalled;
}
public void run() {
this.runWasCalled = true;
synchronized (monitor) {
monitor.notifyAll();
}
}
}
public void run() {
this.runWasCalled = true;
synchronized (monitor) {
monitor.notifyAll();
}
}
}
private static final class NoOpRunnable implements Runnable {
private static final class NoOpRunnable implements Runnable {
public void run() {
// explicit no-op
}
}
public void run() {
// explicit no-op
}
}
}
......@@ -22,7 +22,7 @@ package org.springframework.scripting;
* @author Rick Evans
*/
public interface ScriptBean {
String getName();
void setName(String name);
......@@ -30,5 +30,5 @@ public interface ScriptBean {
int getAge();
void setAge(int age);
}
......@@ -55,239 +55,239 @@ import org.testng.annotations.Test;
@Ignore // renamed to Tests_ to avoid being picked up by junit. Spring Build support for TestNG is pending.
@ContextConfiguration
public class ConcreteTransactionalTestNGSpringContextTests_ extends AbstractTransactionalTestNGSpringContextTests
implements BeanNameAware, InitializingBean {
implements BeanNameAware, InitializingBean {
// ------------------------------------------------------------------------|
// --- CONSTANTS ----------------------------------------------------------|
// ------------------------------------------------------------------------|
// ------------------------------------------------------------------------|
// --- CONSTANTS ----------------------------------------------------------|
// ------------------------------------------------------------------------|
private static final String BOB = "bob";
private static final String JANE = "jane";
private static final String SUE = "sue";
private static final String YODA = "yoda";
private static final String BOB = "bob";
private static final String JANE = "jane";
private static final String SUE = "sue";
private static final String YODA = "yoda";
// ------------------------------------------------------------------------|
// --- STATIC VARIABLES ---------------------------------------------------|
// ------------------------------------------------------------------------|
// ------------------------------------------------------------------------|
// --- STATIC VARIABLES ---------------------------------------------------|
// ------------------------------------------------------------------------|
private static int numSetUpCalls = 0;
private static int numSetUpCallsInTransaction = 0;
private static int numTearDownCalls = 0;
private static int numTearDownCallsInTransaction = 0;
private static int numSetUpCalls = 0;
private static int numSetUpCallsInTransaction = 0;
private static int numTearDownCalls = 0;
private static int numTearDownCallsInTransaction = 0;
// ------------------------------------------------------------------------|
// --- INSTANCE VARIABLES -------------------------------------------------|
// ------------------------------------------------------------------------|
// ------------------------------------------------------------------------|
// --- INSTANCE VARIABLES -------------------------------------------------|
// ------------------------------------------------------------------------|
private boolean beanInitialized = false;
private boolean beanInitialized = false;
private String beanName = "replace me with [" + getClass().getName() + "]";
private Employee employee;
@Autowired
private Pet pet;
@Autowired(required = false)
protected Long nonrequiredLong;
@Resource()
protected String foo;
protected String bar;
// ------------------------------------------------------------------------|
// --- STATIC METHODS -----------------------------------------------------|
// ------------------------------------------------------------------------|
private static int clearPersonTable(SimpleJdbcTemplate simpleJdbcTemplate) {
return SimpleJdbcTestUtils.deleteFromTables(simpleJdbcTemplate, "person");
}
private static void createPersonTable(SimpleJdbcTemplate simpleJdbcTemplate) {
try {
simpleJdbcTemplate.update("CREATE TABLE person (name VARCHAR(20) NOT NULL, PRIMARY KEY(name))");
}
catch (BadSqlGrammarException bsge) {
/* ignore */
}
}
private static int countRowsInPersonTable(SimpleJdbcTemplate simpleJdbcTemplate) {
return SimpleJdbcTestUtils.countRowsInTable(simpleJdbcTemplate, "person");
}
private static int addPerson(SimpleJdbcTemplate simpleJdbcTemplate, String name) {
return simpleJdbcTemplate.update("INSERT INTO person VALUES(?)", name);
}
private static int deletePerson(SimpleJdbcTemplate simpleJdbcTemplate, String name) {
return simpleJdbcTemplate.update("DELETE FROM person WHERE name=?", name);
}
// ------------------------------------------------------------------------|
// --- INSTANCE METHODS ---------------------------------------------------|
// ------------------------------------------------------------------------|
public void afterPropertiesSet() throws Exception {
this.beanInitialized = true;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
@Autowired
protected void setEmployee(Employee employee) {
this.employee = employee;
}
@Resource
protected void setBar(String bar) {
this.bar = bar;
}
// ------------------------------------------------------------------------|
private void assertNumRowsInPersonTable(int expectedNumRows, String testState) {
assertEquals(countRowsInPersonTable(this.simpleJdbcTemplate), expectedNumRows,
"Verifying the number of rows in the person table (" + testState + ").");
}
private void assertAddPerson(final String name) {
assertEquals(addPerson(this.simpleJdbcTemplate, name), 1, "Adding '" + name + "'");
}
// ------------------------------------------------------------------------|
@BeforeClass
public void beforeClass() {
numSetUpCalls = 0;
numSetUpCallsInTransaction = 0;
numTearDownCalls = 0;
numTearDownCallsInTransaction = 0;
}
@AfterClass
public void afterClass() {
assertEquals(numSetUpCalls, 8, "Verifying number of calls to setUp().");
assertEquals(numSetUpCallsInTransaction, 1, "Verifying number of calls to setUp() within a transaction.");
assertEquals(numTearDownCalls, 8, "Verifying number of calls to tearDown().");
assertEquals(numTearDownCallsInTransaction, 1, "Verifying number of calls to tearDown() within a transaction.");
}
@Test
@NotTransactional
public void verifyApplicationContextSet() {
assertInTransaction(false);
assertNotNull(super.applicationContext,
"The application context should have been set due to ApplicationContextAware semantics.");
Employee employeeBean = (Employee) super.applicationContext.getBean("employee");
assertEquals(employeeBean.getName(), "John Smith", "Verifying employee's name.");
}
@Test
@NotTransactional
public void verifyBeanInitialized() {
assertInTransaction(false);
assertTrue(this.beanInitialized,
"This test instance should have been initialized due to InitializingBean semantics.");
}
@Test
@NotTransactional
public void verifyBeanNameSet() {
assertInTransaction(false);
assertEquals(this.beanName, getClass().getName(),
"The bean name of this test instance should have been set due to BeanNameAware semantics.");
}
@Test
@NotTransactional
public void verifyAnnotationAutowiredFields() {
assertInTransaction(false);
assertNull(this.nonrequiredLong, "The nonrequiredLong field should NOT have been autowired.");
assertNotNull(this.pet, "The pet field should have been autowired.");
assertEquals(this.pet.getName(), "Fido", "Verifying pet's name.");
}
@Test
@NotTransactional
public void verifyAnnotationAutowiredMethods() {
assertInTransaction(false);
assertNotNull(this.employee, "The setEmployee() method should have been autowired.");
assertEquals(this.employee.getName(), "John Smith", "Verifying employee's name.");
}
@Test
@NotTransactional
public void verifyResourceAnnotationInjectedFields() {
assertInTransaction(false);
assertEquals(this.foo, "Foo", "The foo field should have been injected via @Resource.");
}
@Test
@NotTransactional
public void verifyResourceAnnotationInjectedMethods() {
assertInTransaction(false);
assertEquals(this.bar, "Bar", "The setBar() method should have been injected via @Resource.");
}
// ------------------------------------------------------------------------|
@BeforeTransaction
public void beforeTransaction() {
assertNumRowsInPersonTable(1, "before a transactional test method");
assertAddPerson(YODA);
}
@BeforeMethod
public void setUp() throws Exception {
numSetUpCalls++;
if (inTransaction()) {
numSetUpCallsInTransaction++;
}
assertNumRowsInPersonTable((inTransaction() ? 2 : 1), "before a test method");
}
@Test
public void modifyTestDataWithinTransaction() {
assertInTransaction(true);
assertAddPerson(JANE);
assertAddPerson(SUE);
assertNumRowsInPersonTable(4, "in modifyTestDataWithinTransaction()");
}
@AfterMethod
public void tearDown() throws Exception {
numTearDownCalls++;
if (inTransaction()) {
numTearDownCallsInTransaction++;
}
assertNumRowsInPersonTable((inTransaction() ? 4 : 1), "after a test method");
}
@AfterTransaction
public void afterTransaction() {
assertEquals(deletePerson(this.simpleJdbcTemplate, YODA), 1, "Deleting yoda");
assertNumRowsInPersonTable(1, "after a transactional test method");
}
// ------------------------------------------------------------------------|
// --- TYPES --------------------------------------------------------------|
// ------------------------------------------------------------------------|
public static class DatabaseSetup {
@Autowired
void setDataSource(DataSource dataSource) {
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
createPersonTable(simpleJdbcTemplate);
clearPersonTable(simpleJdbcTemplate);
addPerson(simpleJdbcTemplate, BOB);
}
}
private String beanName = "replace me with [" + getClass().getName() + "]";
private Employee employee;
@Autowired
private Pet pet;
@Autowired(required = false)
protected Long nonrequiredLong;
@Resource()
protected String foo;
protected String bar;
// ------------------------------------------------------------------------|
// --- STATIC METHODS -----------------------------------------------------|
// ------------------------------------------------------------------------|
private static int clearPersonTable(SimpleJdbcTemplate simpleJdbcTemplate) {
return SimpleJdbcTestUtils.deleteFromTables(simpleJdbcTemplate, "person");
}
private static void createPersonTable(SimpleJdbcTemplate simpleJdbcTemplate) {
try {
simpleJdbcTemplate.update("CREATE TABLE person (name VARCHAR(20) NOT NULL, PRIMARY KEY(name))");
}
catch (BadSqlGrammarException bsge) {
/* ignore */
}
}
private static int countRowsInPersonTable(SimpleJdbcTemplate simpleJdbcTemplate) {
return SimpleJdbcTestUtils.countRowsInTable(simpleJdbcTemplate, "person");
}
private static int addPerson(SimpleJdbcTemplate simpleJdbcTemplate, String name) {
return simpleJdbcTemplate.update("INSERT INTO person VALUES(?)", name);
}
private static int deletePerson(SimpleJdbcTemplate simpleJdbcTemplate, String name) {
return simpleJdbcTemplate.update("DELETE FROM person WHERE name=?", name);
}
// ------------------------------------------------------------------------|
// --- INSTANCE METHODS ---------------------------------------------------|
// ------------------------------------------------------------------------|
public void afterPropertiesSet() throws Exception {
this.beanInitialized = true;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
@Autowired
protected void setEmployee(Employee employee) {
this.employee = employee;
}
@Resource
protected void setBar(String bar) {
this.bar = bar;
}
// ------------------------------------------------------------------------|
private void assertNumRowsInPersonTable(int expectedNumRows, String testState) {
assertEquals(countRowsInPersonTable(this.simpleJdbcTemplate), expectedNumRows,
"Verifying the number of rows in the person table (" + testState + ").");
}
private void assertAddPerson(final String name) {
assertEquals(addPerson(this.simpleJdbcTemplate, name), 1, "Adding '" + name + "'");
}
// ------------------------------------------------------------------------|
@BeforeClass
public void beforeClass() {
numSetUpCalls = 0;
numSetUpCallsInTransaction = 0;
numTearDownCalls = 0;
numTearDownCallsInTransaction = 0;
}
@AfterClass
public void afterClass() {
assertEquals(numSetUpCalls, 8, "Verifying number of calls to setUp().");
assertEquals(numSetUpCallsInTransaction, 1, "Verifying number of calls to setUp() within a transaction.");
assertEquals(numTearDownCalls, 8, "Verifying number of calls to tearDown().");
assertEquals(numTearDownCallsInTransaction, 1, "Verifying number of calls to tearDown() within a transaction.");
}
@Test
@NotTransactional
public void verifyApplicationContextSet() {
assertInTransaction(false);
assertNotNull(super.applicationContext,
"The application context should have been set due to ApplicationContextAware semantics.");
Employee employeeBean = (Employee) super.applicationContext.getBean("employee");
assertEquals(employeeBean.getName(), "John Smith", "Verifying employee's name.");
}
@Test
@NotTransactional
public void verifyBeanInitialized() {
assertInTransaction(false);
assertTrue(this.beanInitialized,
"This test instance should have been initialized due to InitializingBean semantics.");
}
@Test
@NotTransactional
public void verifyBeanNameSet() {
assertInTransaction(false);
assertEquals(this.beanName, getClass().getName(),
"The bean name of this test instance should have been set due to BeanNameAware semantics.");
}
@Test
@NotTransactional
public void verifyAnnotationAutowiredFields() {
assertInTransaction(false);
assertNull(this.nonrequiredLong, "The nonrequiredLong field should NOT have been autowired.");
assertNotNull(this.pet, "The pet field should have been autowired.");
assertEquals(this.pet.getName(), "Fido", "Verifying pet's name.");
}
@Test
@NotTransactional
public void verifyAnnotationAutowiredMethods() {
assertInTransaction(false);
assertNotNull(this.employee, "The setEmployee() method should have been autowired.");
assertEquals(this.employee.getName(), "John Smith", "Verifying employee's name.");
}
@Test
@NotTransactional
public void verifyResourceAnnotationInjectedFields() {
assertInTransaction(false);
assertEquals(this.foo, "Foo", "The foo field should have been injected via @Resource.");
}
@Test
@NotTransactional
public void verifyResourceAnnotationInjectedMethods() {
assertInTransaction(false);
assertEquals(this.bar, "Bar", "The setBar() method should have been injected via @Resource.");
}
// ------------------------------------------------------------------------|
@BeforeTransaction
public void beforeTransaction() {
assertNumRowsInPersonTable(1, "before a transactional test method");
assertAddPerson(YODA);
}
@BeforeMethod
public void setUp() throws Exception {
numSetUpCalls++;
if (inTransaction()) {
numSetUpCallsInTransaction++;
}
assertNumRowsInPersonTable((inTransaction() ? 2 : 1), "before a test method");
}
@Test
public void modifyTestDataWithinTransaction() {
assertInTransaction(true);
assertAddPerson(JANE);
assertAddPerson(SUE);
assertNumRowsInPersonTable(4, "in modifyTestDataWithinTransaction()");
}
@AfterMethod
public void tearDown() throws Exception {
numTearDownCalls++;
if (inTransaction()) {
numTearDownCallsInTransaction++;
}
assertNumRowsInPersonTable((inTransaction() ? 4 : 1), "after a test method");
}
@AfterTransaction
public void afterTransaction() {
assertEquals(deletePerson(this.simpleJdbcTemplate, YODA), 1, "Deleting yoda");
assertNumRowsInPersonTable(1, "after a transactional test method");
}
// ------------------------------------------------------------------------|
// --- TYPES --------------------------------------------------------------|
// ------------------------------------------------------------------------|
public static class DatabaseSetup {
@Autowired
void setDataSource(DataSource dataSource) {
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
createPersonTable(simpleJdbcTemplate);
clearPersonTable(simpleJdbcTemplate);
addPerson(simpleJdbcTemplate, BOB);
}
}
}
......@@ -41,8 +41,8 @@ import org.springframework.transaction.TransactionDefinition;
* @see org.springframework.transaction.interceptor.TransactionProxyFactoryBean
*/
public final class TransactionAttributeSourceTests {
@Test
@Test
public void testMatchAlwaysTransactionAttributeSource() throws Exception {
MatchAlwaysTransactionAttributeSource tas = new MatchAlwaysTransactionAttributeSource();
TransactionAttribute ta = tas.getTransactionAttribute(
......@@ -57,8 +57,8 @@ public final class TransactionAttributeSourceTests {
assertTrue(TransactionDefinition.PROPAGATION_SUPPORTS == ta.getPropagationBehavior());
}
@Ignore
@Test
@Ignore
@Test
public void testMethodMapTransactionAttributeSource() throws NoSuchMethodException {
MethodMapTransactionAttributeSource tas = new MethodMapTransactionAttributeSource();
Map methodMap = new HashMap();
......@@ -76,8 +76,8 @@ public final class TransactionAttributeSourceTests {
assertEquals(TransactionDefinition.PROPAGATION_SUPPORTS, ta.getPropagationBehavior());
}
@Ignore
@Test
@Ignore
@Test
public void testMethodMapTransactionAttributeSourceWithLazyInit() throws NoSuchMethodException {
MethodMapTransactionAttributeSource tas = new MethodMapTransactionAttributeSource();
Map methodMap = new HashMap();
......@@ -94,8 +94,8 @@ public final class TransactionAttributeSourceTests {
assertEquals(TransactionDefinition.PROPAGATION_SUPPORTS, ta.getPropagationBehavior());
}
@Ignore
@Test
@Ignore
@Test
public void testNameMatchTransactionAttributeSource() throws NoSuchMethodException {
NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource();
Map methodMap = new HashMap();
......@@ -111,7 +111,7 @@ public final class TransactionAttributeSourceTests {
assertEquals(TransactionDefinition.PROPAGATION_SUPPORTS, ta.getPropagationBehavior());
}
@Test
@Test
public void testNameMatchTransactionAttributeSourceWithStarAtStartOfMethodName() throws NoSuchMethodException {
NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource();
Properties attributes = new Properties();
......@@ -123,7 +123,7 @@ public final class TransactionAttributeSourceTests {
assertEquals(TransactionDefinition.PROPAGATION_REQUIRED, ta.getPropagationBehavior());
}
@Test
@Test
public void testNameMatchTransactionAttributeSourceWithStarAtEndOfMethodName() throws NoSuchMethodException {
NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource();
Properties attributes = new Properties();
......@@ -135,7 +135,7 @@ public final class TransactionAttributeSourceTests {
assertEquals(TransactionDefinition.PROPAGATION_REQUIRED, ta.getPropagationBehavior());
}
@Test
@Test
public void testNameMatchTransactionAttributeSourceMostSpecificMethodNameIsDefinitelyMatched() throws NoSuchMethodException {
NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource();
Properties attributes = new Properties();
......@@ -148,7 +148,7 @@ public final class TransactionAttributeSourceTests {
assertEquals(TransactionDefinition.PROPAGATION_MANDATORY, ta.getPropagationBehavior());
}
@Test
@Test
public void testNameMatchTransactionAttributeSourceWithEmptyMethodName() throws NoSuchMethodException {
NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource();
Properties attributes = new Properties();
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册