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(),
53 new Class[]{Logger.class}, ih);
54 log.setDelegate(proxyLogger);
55
56 invokeMethods(log);
57
58
59 expectedMethodSignatures.removeAll(ih.getInvokedMethodSignatures());
60 if (!expectedMethodSignatures.isEmpty()) {
61 fail("Following methods are not delegated " + expectedMethodSignatures.toString());
62 }
63 }
64
65 private void invokeMethods(Logger proxyLogger) throws InvocationTargetException, IllegalAccessException {
66 for (Method m : Logger.class.getDeclaredMethods()) {
67 if (!EXCLUDED_METHODS.contains(m.getName())) {
68 m.invoke(proxyLogger, new Object[m.getParameterTypes().length]);
69 }
70 }
71 }
72
73 private class LoggerInvocationHandler implements InvocationHandler {
74 private final Set<String> invokedMethodSignatures = new HashSet<String>();
75
76 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
77 invokedMethodSignatures.add(getMethodSignature(method));
78 if (method.getName().startsWith("is")) {
79 return true;
80 }
81 return null;
82 }
83
84 public Set<String> getInvokedMethodSignatures() {
85 return invokedMethodSignatures;
86 }
87 }
88
89 private static Set<String> determineMethodSignatures(Class<Logger> loggerClass) {
90 Set<String> methodSignatures = new HashSet<String>();
91 for (Method m : loggerClass.getDeclaredMethods()) {
92 if (!EXCLUDED_METHODS.contains(m.getName())) {
93 methodSignatures.add(getMethodSignature(m));
94 }
95 }
96 return methodSignatures;
97 }
98
99 private static String getMethodSignature(Method m) {
100 List<String> result = new ArrayList<String>();
101 result.add(m.getName());
102 for (Class<?> clazz : m.getParameterTypes()) {
103 result.add(clazz.getSimpleName());
104 }
105 return result.toString();
106 }
107 }