1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package org.slf4j.helpers;
26
27 import java.lang.reflect.InvocationHandler;
28 import java.lang.reflect.InvocationTargetException;
29 import java.lang.reflect.Method;
30 import java.lang.reflect.Proxy;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.HashSet;
34 import java.util.List;
35 import java.util.Set;
36
37 import junit.framework.TestCase;
38 import org.slf4j.Logger;
39
40
41
42
43 public class SubstitutableLoggerTest extends TestCase {
44 private static final Set<String> EXCLUDED_METHODS = new HashSet<String>(Arrays.asList("getName"));
45
46 public void testDelegate() throws Exception {
47 SubstituteLogger log = new SubstituteLogger("foo");
48 assertTrue(log.delegate() instanceof NOPLogger);
49
50 Set<String> expectedMethodSignatures = determineMethodSignatures(Logger.class);
51 LoggerInvocationHandler ih = new LoggerInvocationHandler();
52 Logger proxyLogger = (Logger) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Logger.class }, ih);
53 log.setDelegate(proxyLogger);
54
55 invokeMethods(log);
56
57
58 expectedMethodSignatures.removeAll(ih.getInvokedMethodSignatures());
59 if (!expectedMethodSignatures.isEmpty()) {
60 fail("Following methods are not delegated " + expectedMethodSignatures.toString());
61 }
62 }
63
64 private void invokeMethods(Logger proxyLogger) throws InvocationTargetException, IllegalAccessException {
65 for (Method m : Logger.class.getDeclaredMethods()) {
66 if (!EXCLUDED_METHODS.contains(m.getName())) {
67 m.invoke(proxyLogger, new Object[m.getParameterTypes().length]);
68 }
69 }
70 }
71
72 private class LoggerInvocationHandler implements InvocationHandler {
73 private final Set<String> invokedMethodSignatures = new HashSet<String>();
74
75 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
76 invokedMethodSignatures.add(getMethodSignature(method));
77 if (method.getName().startsWith("is")) {
78 return true;
79 }
80 return null;
81 }
82
83 public Set<String> getInvokedMethodSignatures() {
84 return invokedMethodSignatures;
85 }
86 }
87
88 private static Set<String> determineMethodSignatures(Class<Logger> loggerClass) {
89 Set<String> methodSignatures = new HashSet<String>();
90 for (Method m : loggerClass.getDeclaredMethods()) {
91 if (!EXCLUDED_METHODS.contains(m.getName())) {
92 methodSignatures.add(getMethodSignature(m));
93 }
94 }
95 return methodSignatures;
96 }
97
98 private static String getMethodSignature(Method m) {
99 List<String> result = new ArrayList<String>();
100 result.add(m.getName());
101 for (Class<?> clazz : m.getParameterTypes()) {
102 result.add(clazz.getSimpleName());
103 }
104 return result.toString();
105 }
106 }