提交 40016fc9 编写于 作者: C Chris Beams

moving unit tests from .testsuite -> .aop

上级 be3ecf5f
......@@ -16,8 +16,13 @@
package org.springframework.aop.framework;
import junit.framework.TestCase;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.*;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.Test;
import org.springframework.aop.Advisor;
import org.springframework.aop.interceptor.DebugInterceptor;
import org.springframework.aop.interceptor.NopInterceptor;
......@@ -27,17 +32,18 @@ import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.IOther;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.transaction.interceptor.TransactionInterceptor;
/**
* Also tests AdvisedSupport and ProxyCreatorSupport superclasses.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Chris Beams
* @since 14.05.2003
*/
public class ProxyFactoryTests extends TestCase {
public class ProxyFactoryTests {
@Test
public void testIndexOfMethods() {
TestBean target = new TestBean();
ProxyFactory pf = new ProxyFactory(target);
......@@ -53,6 +59,7 @@ public class ProxyFactoryTests extends TestCase {
assertEquals(-1, advised.indexOf(new DefaultPointcutAdvisor(null)));
}
@Test
public void testRemoveAdvisorByReference() {
TestBean target = new TestBean();
ProxyFactory pf = new ProxyFactory(target);
......@@ -72,6 +79,7 @@ public class ProxyFactoryTests extends TestCase {
assertFalse(pf.removeAdvisor(new DefaultPointcutAdvisor(null)));
}
@Test
public void testRemoveAdvisorByIndex() {
TestBean target = new TestBean();
ProxyFactory pf = new ProxyFactory(target);
......@@ -119,6 +127,7 @@ public class ProxyFactoryTests extends TestCase {
assertEquals(4, nop2.getCount());
}
@Test
public void testReplaceAdvisor() {
TestBean target = new TestBean();
ProxyFactory pf = new ProxyFactory(target);
......@@ -147,6 +156,7 @@ public class ProxyFactoryTests extends TestCase {
assertFalse(pf.replaceAdvisor(new DefaultPointcutAdvisor(null), advisor1));
}
@Test
public void testAddRepeatedInterface() {
TimeStamped tst = new TimeStamped() {
public long getTimeStamp() {
......@@ -158,22 +168,23 @@ public class ProxyFactoryTests extends TestCase {
// This call should be ignored without error
pf.addInterface(TimeStamped.class);
// All cool
TimeStamped ts = (TimeStamped) pf.getProxy();
assertThat(pf.getProxy(), instanceOf(TimeStamped.class));
}
@Test
public void testGetsAllInterfaces() throws Exception {
// Extend to get new interface
class TestBeanSubclass extends TestBean implements Comparable {
class TestBeanSubclass extends TestBean implements Comparable<Object> {
public int compareTo(Object arg0) {
throw new UnsupportedOperationException("compareTo");
}
}
TestBeanSubclass raw = new TestBeanSubclass();
ProxyFactory factory = new ProxyFactory(raw);
assertEquals("Found correct number of interfaces", 5, factory.getProxiedInterfaces().length);
//System.out.println("Proxied interfaces are " + StringUtils.arrayToDelimitedString(factory.getProxiedInterfaces(), ","));
assertEquals("Found correct number of interfaces", 3, factory.getProxiedInterfaces().length);
ITestBean tb = (ITestBean) factory.getProxy();
assertTrue("Picked up secondary interface", tb instanceof IOther);
assertThat("Picked up secondary interface", tb, instanceOf(IOther.class));
raw.setAge(25);
assertTrue(tb.getAge() == raw.getAge());
......@@ -181,11 +192,11 @@ public class ProxyFactoryTests extends TestCase {
long t = 555555L;
TimestampIntroductionInterceptor ti = new TimestampIntroductionInterceptor(t);
Class[] oldProxiedInterfaces = factory.getProxiedInterfaces();
Class<?>[] oldProxiedInterfaces = factory.getProxiedInterfaces();
factory.addAdvisor(0, new DefaultIntroductionAdvisor(ti, TimeStamped.class));
Class[] newProxiedInterfaces = factory.getProxiedInterfaces();
Class<?>[] newProxiedInterfaces = factory.getProxiedInterfaces();
assertEquals("Advisor proxies one more interface after introduction", oldProxiedInterfaces.length + 1, newProxiedInterfaces.length);
TimeStamped ts = (TimeStamped) factory.getProxy();
......@@ -194,16 +205,23 @@ public class ProxyFactoryTests extends TestCase {
((IOther) ts).absquatulate();
}
@Test
public void testInterceptorInclusionMethods() {
class MyInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
throw new UnsupportedOperationException();
}
}
NopInterceptor di = new NopInterceptor();
NopInterceptor diUnused = new NopInterceptor();
ProxyFactory factory = new ProxyFactory(new TestBean());
factory.addAdvice(0, di);
ITestBean tb = (ITestBean) factory.getProxy();
assertThat(factory.getProxy(), instanceOf(ITestBean.class));
assertTrue(factory.adviceIncluded(di));
assertTrue(!factory.adviceIncluded(diUnused));
assertTrue(factory.countAdvicesOfType(NopInterceptor.class) == 1);
assertTrue(factory.countAdvicesOfType(TransactionInterceptor.class) == 0);
assertTrue(factory.countAdvicesOfType(MyInterceptor.class) == 0);
factory.addAdvice(0, diUnused);
assertTrue(factory.adviceIncluded(diUnused));
......@@ -213,6 +231,7 @@ public class ProxyFactoryTests extends TestCase {
/**
* Should see effect immediately on behavior.
*/
@Test
public void testCanAddAndRemoveAspectInterfacesOnSingleton() {
ProxyFactory config = new ProxyFactory(new TestBean());
......@@ -264,6 +283,7 @@ public class ProxyFactoryTests extends TestCase {
assertTrue(debugInterceptor.getCount() == 1);
}
@Test
public void testProxyTargetClassWithInterfaceAsTarget() {
ProxyFactory pf = new ProxyFactory();
pf.setTargetClass(ITestBean.class);
......@@ -273,6 +293,7 @@ public class ProxyFactoryTests extends TestCase {
assertTrue(proxy instanceof ITestBean);
}
@Test
public void testProxyTargetClassWithConcreteClassAsTarget() {
ProxyFactory pf = new ProxyFactory();
pf.setTargetClass(TestBean.class);
......
......@@ -14,26 +14,21 @@
* limitations under the License.
*/
package org.springframework.aop.interceptor;
import junit.framework.TestCase;
import org.springframework.beans.ITestBean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
package org.springframework.aop.framework;
/**
* Non-XML tests are in AbstractAopProxyTests
* This interface can be implemented by cacheable objects or cache entries,
* to enable the freshness of objects to be checked.
*
* @author Rod Johnson
*/
public class ExposeInvocationInterceptorTests extends TestCase {
public void testXmlConfig() {
ClassPathXmlApplicationContext xac = new ClassPathXmlApplicationContext("org/springframework/aop/interceptor/exposeInvocation.xml");
ITestBean tb = (ITestBean) xac.getBean("proxy");
String name= "tony";
tb.setName(name);
// Fires context checks
assertEquals(name, tb.getName());
}
public interface TimeStamped {
/**
* Return the timestamp for this object.
* @return long the timestamp for this object,
* as returned by System.currentTimeMillis()
*/
long getTimeStamp();
}
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.framework;
import org.springframework.aop.support.DelegatingIntroductionInterceptor;
public class TimestampIntroductionInterceptor extends DelegatingIntroductionInterceptor
implements TimeStamped {
private long ts;
public TimestampIntroductionInterceptor() {
}
public TimestampIntroductionInterceptor(long ts) {
this.ts = ts;
}
public void setTime(long ts) {
this.ts = ts;
}
public long getTimeStamp() {
return ts;
}
}
/*
* The Spring Framework is published under the terms
* of the Apache Software License.
*/
package org.springframework.util;
import java.awt.Point;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import junit.framework.TestCase;
import org.springframework.beans.TestBean;
/**
* Utilities for testing serializability of objects.
* Exposes static methods for use in other test cases.
* Extends TestCase only to test itself.
*
* @author Rod Johnson
*/
public class SerializationTestUtils extends TestCase {
public static void testSerialization(Object o) throws IOException {
OutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
}
public static boolean isSerializable(Object o) throws IOException {
try {
testSerialization(o);
return true;
}
catch (NotSerializableException ex) {
return false;
}
}
public static Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.flush();
baos.flush();
byte[] bytes = baos.toByteArray();
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(is);
Object o2 = ois.readObject();
return o2;
}
public SerializationTestUtils(String s) {
super(s);
}
public void testWithNonSerializableObject() throws IOException {
TestBean o = new TestBean();
assertFalse(o instanceof Serializable);
assertFalse(isSerializable(o));
try {
testSerialization(o);
fail();
}
catch (NotSerializableException ex) {
// Ok
}
}
public void testWithSerializableObject() throws Exception {
int x = 5;
int y = 10;
Point p = new Point(x, y);
assertTrue(p instanceof Serializable);
testSerialization(p);
assertTrue(isSerializable(p));
Point p2 = (Point) serializeAndDeserialize(p);
assertNotSame(p, p2);
assertEquals(x, (int) p2.getX());
assertEquals(y, (int) p2.getY());
}
}
......@@ -22,9 +22,6 @@ import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.ITestBean;
/**
*
*/
public class InvocationCheckExposedInvocationTestBean extends ExposedInvocationTestBean {
protected void assertions(MethodInvocation invocation) {
TestCase.assertTrue(invocation.getThis() == this);
......
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.interceptor;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.DerivedTestBean;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.util.SerializationTestUtils;
/**
* @author Juergen Hoeller
* @since 06.04.2004
*/
public class ConcurrencyThrottleInterceptorTests extends TestCase {
protected static final Log logger = LogFactory.getLog(ConcurrencyThrottleInterceptorTests.class);
public static final int NR_OF_THREADS = 100;
public static final int NR_OF_ITERATIONS = 1000;
public void testSerializable() throws Exception {
DerivedTestBean tb = new DerivedTestBean();
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setInterfaces(new Class[] {ITestBean.class});
ConcurrencyThrottleInterceptor cti = new ConcurrencyThrottleInterceptor();
proxyFactory.addAdvice(cti);
proxyFactory.setTarget(tb);
ITestBean proxy = (ITestBean) proxyFactory.getProxy();
proxy.getAge();
ITestBean serializedProxy = (ITestBean) SerializationTestUtils.serializeAndDeserialize(proxy);
Advised advised = (Advised) serializedProxy;
ConcurrencyThrottleInterceptor serializedCti =
(ConcurrencyThrottleInterceptor) advised.getAdvisors()[0].getAdvice();
assertEquals(cti.getConcurrencyLimit(), serializedCti.getConcurrencyLimit());
serializedProxy.getAge();
}
public void testMultipleThreadsWithLimit1() {
testMultipleThreads(1);
}
public void testMultipleThreadsWithLimit10() {
testMultipleThreads(10);
}
private void testMultipleThreads(int concurrencyLimit) {
TestBean tb = new TestBean();
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setInterfaces(new Class[] {ITestBean.class});
ConcurrencyThrottleInterceptor cti = new ConcurrencyThrottleInterceptor();
cti.setConcurrencyLimit(concurrencyLimit);
proxyFactory.addAdvice(cti);
proxyFactory.setTarget(tb);
ITestBean proxy = (ITestBean) proxyFactory.getProxy();
Thread[] threads = new Thread[NR_OF_THREADS];
for (int i = 0; i < NR_OF_THREADS; i++) {
threads[i] = new ConcurrencyThread(proxy, null);
threads[i].start();
}
for (int i = 0; i < NR_OF_THREADS / 10; i++) {
try {
Thread.sleep(5);
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
threads[i] = new ConcurrencyThread(proxy,
i % 2 == 0 ? (Throwable) new OutOfMemoryError() : (Throwable) new IllegalStateException());
threads[i].start();
}
for (int i = 0; i < NR_OF_THREADS; i++) {
try {
threads[i].join();
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
private static class ConcurrencyThread extends Thread {
private ITestBean proxy;
private Throwable ex;
public ConcurrencyThread(ITestBean proxy, Throwable ex) {
this.proxy = proxy;
this.ex = ex;
}
public void run() {
if (this.ex != null) {
try {
this.proxy.exceptional(this.ex);
}
catch (RuntimeException ex) {
if (ex == this.ex) {
logger.debug("Expected exception thrown", ex);
}
else {
// should never happen
ex.printStackTrace();
}
}
catch (Error err) {
if (err == this.ex) {
logger.debug("Expected exception thrown", err);
}
else {
// should never happen
ex.printStackTrace();
}
}
catch (Throwable ex) {
// should never happen
ex.printStackTrace();
}
}
else {
for (int i = 0; i < NR_OF_ITERATIONS; i++) {
this.proxy.getName();
}
}
logger.debug("finished");
}
}
}
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.interceptor;
import java.lang.reflect.Method;
import junit.framework.TestCase;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.easymock.MockControl;
import org.springframework.test.AssertThrows;
/**
* @author Rob Harrop
* @author Rick Evans
* @author Juergen Hoeller
*/
public class CustomizableTraceInterceptorTests extends TestCase {
public void testSetEmptyEnterMessage() {
new AssertThrows(IllegalArgumentException.class, "Must not be able to set empty enter message") {
public void test() throws Exception {
new CustomizableTraceInterceptor().setEnterMessage("");
}
}.runTest();
}
public void testSetEnterMessageWithReturnValuePlaceholder() {
new AssertThrows(IllegalArgumentException.class, "Must not be able to set enter message with return value placeholder") {
public void test() throws Exception {
new CustomizableTraceInterceptor().setEnterMessage(CustomizableTraceInterceptor.PLACEHOLDER_RETURN_VALUE);
}
}.runTest();
}
public void testSetEnterMessageWithExceptionPlaceholder() {
new AssertThrows(IllegalArgumentException.class, "Must not be able to set enter message with exception placeholder") {
public void test() throws Exception {
new CustomizableTraceInterceptor().setEnterMessage(CustomizableTraceInterceptor.PLACEHOLDER_EXCEPTION);
}
}.runTest();
}
public void testSetEnterMessageWithInvocationTimePlaceholder() {
new AssertThrows(IllegalArgumentException.class, "Must not be able to set enter message with invocation time placeholder") {
public void test() throws Exception {
new CustomizableTraceInterceptor().setEnterMessage(CustomizableTraceInterceptor.PLACEHOLDER_INVOCATION_TIME);
}
}.runTest();
}
public void testSetEmptyExitMessage() {
new AssertThrows(IllegalArgumentException.class, "Must not be able to set empty exit message") {
public void test() throws Exception {
new CustomizableTraceInterceptor().setExitMessage("");
}
}.runTest();
}
public void testSetExitMessageWithExceptionPlaceholder() {
new AssertThrows(IllegalArgumentException.class, "Must not be able to set exit message with exception placeholder") {
public void test() throws Exception {
new CustomizableTraceInterceptor().setExitMessage(CustomizableTraceInterceptor.PLACEHOLDER_EXCEPTION);
}
}.runTest();
}
public void testSetEmptyExceptionMessage() {
new AssertThrows(IllegalArgumentException.class, "Must not be able to set empty exception message") {
public void test() throws Exception {
new CustomizableTraceInterceptor().setExceptionMessage("");
}
}.runTest();
}
public void testSetExceptionMethodWithReturnValuePlaceholder() {
new AssertThrows(IllegalArgumentException.class, "Must not be able to set exception message with return value placeholder") {
public void test() throws Exception {
new CustomizableTraceInterceptor().setExceptionMessage(CustomizableTraceInterceptor.PLACEHOLDER_RETURN_VALUE);
}
}.runTest();
}
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[]{});
log.isTraceEnabled();
mockLog.setReturnValue(true);
methodInvocation.getMethod();
mockMethodInvocation.setReturnValue(toString, 4);
methodInvocation.getThis();
mockMethodInvocation.setReturnValue(this, 2);
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();
CustomizableTraceInterceptor interceptor = new StubCustomizableTraceInterceptor(log);
interceptor.invoke(methodInvocation);
mockLog.verify();
mockMethodInvocation.verify();
}
public void testExceptionPathLogsCorrectly() 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[]{});
log.isTraceEnabled();
mockLog.setReturnValue(true);
methodInvocation.getMethod();
mockMethodInvocation.setReturnValue(toString, 4);
methodInvocation.getThis();
mockMethodInvocation.setReturnValue(this, 2);
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();
CustomizableTraceInterceptor interceptor = new StubCustomizableTraceInterceptor(log);
try {
interceptor.invoke(methodInvocation);
fail("Must have propagated the IllegalArgumentException.");
}
catch (IllegalArgumentException expected) {
}
mockLog.verify();
mockMethodInvocation.verify();
}
public void testSunnyDayPathLogsCorrectlyWithPrettyMuchAllPlaceholdersMatching() 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[0]);
Object[] arguments = new Object[]{"$ One \\$", new Long(2)};
log.isTraceEnabled();
mockLog.setReturnValue(true);
methodInvocation.getMethod();
mockMethodInvocation.setReturnValue(toString, 7);
methodInvocation.getThis();
mockMethodInvocation.setReturnValue(this, 2);
methodInvocation.getArguments();
mockMethodInvocation.setReturnValue(arguments, 2);
log.trace("Some tracing output");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
methodInvocation.proceed();
mockMethodInvocation.setReturnValue("Hello!");
log.trace("Some more tracing output");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
mockLog.setVoidCallable();
mockMethodInvocation.replay();
mockLog.replay();
CustomizableTraceInterceptor interceptor = new StubCustomizableTraceInterceptor(log);
interceptor.setEnterMessage(new StringBuffer().append("Entering the '").append(CustomizableTraceInterceptor.PLACEHOLDER_METHOD_NAME).append("' method of the [").append(CustomizableTraceInterceptor.PLACEHOLDER_TARGET_CLASS_NAME).append("] class with the following args (").append(CustomizableTraceInterceptor.PLACEHOLDER_ARGUMENTS).append(") and arg types (").append(CustomizableTraceInterceptor.PLACEHOLDER_ARGUMENT_TYPES).append(").").toString());
interceptor.setExitMessage(new StringBuffer().append("Exiting the '").append(CustomizableTraceInterceptor.PLACEHOLDER_METHOD_NAME).append("' method of the [").append(CustomizableTraceInterceptor.PLACEHOLDER_TARGET_CLASS_SHORT_NAME).append("] class with the following args (").append(CustomizableTraceInterceptor.PLACEHOLDER_ARGUMENTS).append(") and arg types (").append(CustomizableTraceInterceptor.PLACEHOLDER_ARGUMENT_TYPES).append("), returning '").append(CustomizableTraceInterceptor.PLACEHOLDER_RETURN_VALUE).append("' and taking '").append(CustomizableTraceInterceptor.PLACEHOLDER_INVOCATION_TIME).append("' this long.").toString());
interceptor.invoke(methodInvocation);
mockLog.verify();
mockMethodInvocation.verify();
}
private static class StubCustomizableTraceInterceptor extends CustomizableTraceInterceptor {
private final Log log;
public StubCustomizableTraceInterceptor(Log log) {
super.setUseDynamicLogger(false);
this.log = log;
}
protected Log getLoggerForInvocation(MethodInvocation invocation) {
return this.log;
}
}
}
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.interceptor;
import junit.framework.TestCase;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.easymock.MockControl;
/**
* Unit tests for the {@link DebugInterceptor} class.
*
* @author Rick Evans
*/
public final class DebugInterceptorTests extends TestCase {
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();
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();
DebugInterceptor interceptor = new StubDebugInterceptor(log);
interceptor.invoke(methodInvocation);
checkCallCountTotal(interceptor);
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();
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();
DebugInterceptor interceptor = new StubDebugInterceptor(log);
try {
interceptor.invoke(methodInvocation);
fail("Must have propagated the IllegalArgumentException.");
} catch (IllegalArgumentException expected) {
}
checkCallCountTotal(interceptor);
mockLog.verify();
mockMethodInvocation.verify();
}
private void checkCallCountTotal(DebugInterceptor interceptor) {
assertEquals("Intercepted call count not being incremented correctly", 1, interceptor.getCount());
}
private static final class StubDebugInterceptor extends DebugInterceptor {
private final Log log;
public StubDebugInterceptor(Log log) {
super(true);
this.log = log;
}
protected Log getLoggerForInvocation(MethodInvocation invocation) {
return log;
}
}
}
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.interceptor;
import junit.framework.TestCase;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.NamedBean;
/**
*
* @author Rod Johnson
*
*/
public class ExposeBeanNameAdvisorsTests extends TestCase {
private class RequiresBeanNameBoundTestBean extends TestBean {
private final String beanName;
public RequiresBeanNameBoundTestBean(String beanName) {
this.beanName = beanName;
}
public int getAge() {
assertEquals(beanName, ExposeBeanNameAdvisors.getBeanName());
return super.getAge();
}
}
public void testNoIntroduction() {
String beanName = "foo";
TestBean target = new RequiresBeanNameBoundTestBean(beanName);
ProxyFactory pf = new ProxyFactory(target);
pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR);
pf.addAdvisor(ExposeBeanNameAdvisors.createAdvisorWithoutIntroduction(beanName));
ITestBean proxy = (ITestBean) pf.getProxy();
assertFalse("No introduction", proxy instanceof NamedBean);
// Requires binding
proxy.getAge();
}
public void testWithIntroduction() {
String beanName = "foo";
TestBean target = new RequiresBeanNameBoundTestBean(beanName);
ProxyFactory pf = new ProxyFactory(target);
pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR);
pf.addAdvisor(ExposeBeanNameAdvisors.createAdvisorIntroducingNamedBean(beanName));
ITestBean proxy = (ITestBean) pf.getProxy();
assertTrue("Introduction was made", proxy instanceof NamedBean);
// Requires binding
proxy.getAge();
NamedBean nb = (NamedBean) proxy;
assertEquals("Name returned correctly", beanName, nb.getBeanName());
}
}
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.interceptor;
import java.lang.reflect.Method;
import junit.framework.TestCase;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.easymock.MockControl;
/**
* @author Rob Harrop
* @author Rick Evans
*/
public class PerformanceMonitorInterceptorTests extends TestCase {
public void testSuffixAndPrefixAssignment() {
PerformanceMonitorInterceptor interceptor = new PerformanceMonitorInterceptor();
assertNotNull(interceptor.getPrefix());
assertNotNull(interceptor.getSuffix());
interceptor.setPrefix(null);
interceptor.setSuffix(null);
assertNotNull(interceptor.getPrefix());
assertNotNull(interceptor.getSuffix());
}
public void testSunnyDayPathLogsPerformanceMetricsCorrectly() 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[0]);
methodInvocation.getMethod();
mockMethodInvocation.setReturnValue(toString);
methodInvocation.proceed();
mockMethodInvocation.setReturnValue(null);
log.trace("Some performance metric");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
mockLog.setVoidCallable();
mockMethodInvocation.replay();
mockLog.replay();
PerformanceMonitorInterceptor interceptor = new PerformanceMonitorInterceptor(true);
interceptor.invokeUnderTrace(methodInvocation, log);
mockLog.verify();
mockMethodInvocation.verify();
}
public void testExceptionPathStillLogsPerformanceMetricsCorrectly() 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[0]);
methodInvocation.getMethod();
mockMethodInvocation.setReturnValue(toString);
methodInvocation.proceed();
mockMethodInvocation.setThrowable(new IllegalArgumentException());
log.trace("Some performance metric");
mockLog.setMatcher(MockControl.ALWAYS_MATCHER);
mockLog.setVoidCallable();
mockMethodInvocation.replay();
mockLog.replay();
PerformanceMonitorInterceptor interceptor = new PerformanceMonitorInterceptor(true);
try {
interceptor.invokeUnderTrace(methodInvocation, log);
fail("Must have propagated the IllegalArgumentException.");
}
catch (IllegalArgumentException expected) {
}
mockLog.verify();
mockMethodInvocation.verify();
}
}
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.interceptor;
import junit.framework.TestCase;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.easymock.MockControl;
import java.lang.reflect.Method;
/**
* Unit tests for the {@link SimpleTraceInterceptor} class.
*
* @author Rick Evans
*/
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();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<!--
Tests for throws advice.
-->
<beans>
<bean id="nopInterceptor" class="org.springframework.aop.interceptor.NopInterceptor"/>
<bean id="exposeInvocation" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
<property name="targetClass">
<value>org.springframework.aop.interceptor.ExposeInvocationInterceptor</value>
</property>
<property name="targetField"><value>INSTANCE</value></property>
</bean>
<bean id="countingBeforeAdvice" class="org.springframework.aop.framework.CountingBeforeAdvice"/>
<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<bean class="org.springframework.aop.framework.InvocationCheckExposedInvocationTestBean" />
</property>
<property name="interceptorNames">
<value>exposeInvocation,countingBeforeAdvice,nopInterceptor</value>
</property>
</bean>
</beans>
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册