1 /*
2  * Copyright (C) 2012 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.util.concurrent;
18 
19 import com.google.common.base.Function;
20 import com.google.common.base.Throwables;
21 import com.google.common.collect.ForwardingObject;
22 import com.google.common.collect.Iterables;
23 import com.google.common.testing.ForwardingWrapperTester;
24 
25 import org.easymock.EasyMock;
26 
27 import java.lang.reflect.Method;
28 import java.util.Arrays;
29 
30 /**
31  * Tester for typical subclass of {@link ForwardingObject} by using EasyMock partial mocks.
32  *
33  * @author Ben Yu
34  */
35 final class ForwardingObjectTester {
36 
37   private static final Method DELEGATE_METHOD;
38   static {
39     try {
40       DELEGATE_METHOD = ForwardingObject.class.getDeclaredMethod("delegate");
41       DELEGATE_METHOD.setAccessible(true);
42     } catch (SecurityException e) {
43       throw new RuntimeException(e);
44     } catch (NoSuchMethodException e) {
45       throw new AssertionError(e);
46     }
47   }
48 
49   /**
50    * Ensures that all interface methods of {@code forwarderClass} are forwarded to the
51    * {@link ForwardingObject#delegate}. {@code forwarderClass} is assumed to only implement one
52    * interface.
53    */
testForwardingObject(final Class<T> forwarderClass)54   static <T extends ForwardingObject> void testForwardingObject(final Class<T> forwarderClass) {
55     @SuppressWarnings("unchecked") // super interface type of T
56     Class<? super T> interfaceType = (Class<? super T>)
57         Iterables.getOnlyElement(Arrays.asList(forwarderClass.getInterfaces()));
58     new ForwardingWrapperTester().testForwarding(interfaceType, new Function<Object, T>() {
59       @Override public T apply(Object delegate) {
60         T mock = EasyMock.createMockBuilder(forwarderClass)
61             .addMockedMethod(DELEGATE_METHOD)
62             .createMock();
63         try {
64           DELEGATE_METHOD.invoke(mock);
65         } catch (Exception e) {
66           throw Throwables.propagate(e);
67         }
68         EasyMock.expectLastCall().andStubReturn(delegate);
69         EasyMock.replay(mock);
70         return mock;
71       }
72     });
73   }
74 }
75