• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 static org.mockito.Answers.CALLS_REAL_METHODS;
20 import static org.mockito.Mockito.doReturn;
21 import static org.mockito.Mockito.mock;
22 
23 import com.google.common.base.Function;
24 import com.google.common.collect.ForwardingObject;
25 import com.google.common.collect.Iterables;
26 import com.google.common.testing.ForwardingWrapperTester;
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 
39   static {
40     try {
41       DELEGATE_METHOD = ForwardingObject.class.getDeclaredMethod("delegate");
42       DELEGATE_METHOD.setAccessible(true);
43     } catch (SecurityException e) {
44       throw new RuntimeException(e);
45     } catch (NoSuchMethodException e) {
46       throw new AssertionError(e);
47     }
48   }
49 
50   /**
51    * Ensures that all interface methods of {@code forwarderClass} are forwarded to the {@link
52    * ForwardingObject#delegate}. {@code forwarderClass} is assumed to only implement one 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 =
57         (Class<? super T>) Iterables.getOnlyElement(Arrays.asList(forwarderClass.getInterfaces()));
58     new ForwardingWrapperTester()
59         .testForwarding(
60             interfaceType,
61             new Function<Object, T>() {
62               @Override
63               public T apply(Object delegate) {
64                 T mock = mock(forwarderClass, CALLS_REAL_METHODS.get());
65                 try {
66                   T stubber = doReturn(delegate).when(mock);
67                   DELEGATE_METHOD.invoke(stubber);
68                 } catch (Exception e) {
69                   throw new RuntimeException(e);
70                 }
71                 return mock;
72               }
73             });
74   }
75 }
76