How to use method of org.easymock.internal.ClassProxyFactory class

Best Easymock code snippet using org.easymock.internal.ClassProxyFactory.

Run Easymock automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package org.jboss.test.faces.mock;
2
3import static org.easymock.classextension.internal.ClassExtensionHelper.getInterceptor;
4import static org.easymock.classextension.internal.ClassExtensionHelper.setCurrentConstructorArgs;
5
6import java.lang.reflect.Method;
7
8import org.easymock.classextension.ConstructorArgs;
9import org.easymock.classextension.IMocksControl;
10import org.easymock.internal.IProxyFactory;
11import org.easymock.internal.MocksControl;
12
13public class FacesMocksClassControl extends MocksControl implements IMocksControl {
14
15    private static final long serialVersionUID = -6032144451192179422L;
16
17    public FacesMocksClassControl(MockType type) {
18        super(type);
19    }
20
21    public <T> T createMock(String name, Class<T> toMock,
22            Method... mockedMethods) {
23
24        if(toMock.isInterface()) {
25            throw new IllegalArgumentException("Partial mocking doesn't make sense for interface");
26        }
27
28        T mock = createMock(name, toMock);
29
30        // Set the mocked methods on the interceptor
31        getInterceptor(mock).setMockedMethods(mockedMethods);
32
33        return mock;
34    }
35
36    public <T> T createMock(Class<T> toMock, Method... mockedMethods) {
37
38        if(toMock.isInterface()) {
39            throw new IllegalArgumentException("Partial mocking doesn't make sense for interface");
40        }
41
42        T mock = createMock(toMock);
43
44        // Set the mocked methods on the interceptor
45        getInterceptor(mock).setMockedMethods(mockedMethods);
46
47        return mock;
48    }
49
50    public <T> T createMock(Class<T> toMock, ConstructorArgs constructorArgs,
51            Method... mockedMethods) {
52        // Trick to allow the ClassProxyFactory to access constructor args
53        setCurrentConstructorArgs(constructorArgs);
54        try {
55            return createMock(toMock, mockedMethods);
56        } finally {
57            setCurrentConstructorArgs(null);
58        }
59    }
60
61    public <T> T createMock(String name, Class<T> toMock,
62            ConstructorArgs constructorArgs, Method... mockedMethods) {
63        // Trick to allow the ClassProxyFactory to access constructor args
64        setCurrentConstructorArgs(constructorArgs);
65        try {
66            return createMock(name, toMock, mockedMethods);
67        } finally {
68            setCurrentConstructorArgs(null);
69        }
70    }
71
72    @Override
73    protected <T> IProxyFactory<T> createProxyFactory(Class<T> toMock) {
74        if (toMock.isInterface()) {
75            return super.createProxyFactory(toMock);
76        }
77        return new FacesClassProxyFactory<T>();
78    }
79}
80
Full Screen
copy
1/*
2 * Copyright 2001-2021 the original author or 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 */
16package org.easymock.internal;
17
18import net.sf.cglib.core.CodeGenerationException;
19import net.sf.cglib.core.CollectionUtils;
20import net.sf.cglib.core.DefaultNamingPolicy;
21import net.sf.cglib.core.NamingPolicy;
22import net.sf.cglib.core.Predicate;
23import net.sf.cglib.core.VisibilityPredicate;
24import net.sf.cglib.proxy.Enhancer;
25import net.sf.cglib.proxy.Factory;
26import net.sf.cglib.proxy.MethodInterceptor;
27import net.sf.cglib.proxy.MethodProxy;
28import org.easymock.ConstructorArgs;
29
30import java.io.IOException;
31import java.io.Serializable;
32import java.lang.reflect.Constructor;
33import java.lang.reflect.InvocationHandler;
34import java.lang.reflect.InvocationTargetException;
35import java.lang.reflect.Method;
36import java.lang.reflect.Modifier;
37import java.security.AccessController;
38import java.security.PrivilegedAction;
39import java.util.Arrays;
40import java.util.HashSet;
41import java.util.List;
42import java.util.Set;
43
44/**
45 * Factory generating a mock for a class.
46 *
47 * @author Henri Tremblay
48 */
49public class ClassProxyFactory implements IProxyFactory {
50
51    public static class MockMethodInterceptor implements MethodInterceptor, Serializable {
52
53        private static final long serialVersionUID = -9054190871232972342L;
54
55        private final InvocationHandler handler;
56
57        private transient Set<Method> mockedMethods;
58
59        public MockMethodInterceptor(InvocationHandler handler) {
60            this.handler = handler;
61        }
62
63        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
64                throws Throwable {
65
66            // We conveniently mock abstract methods be default
67            if (Modifier.isAbstract(method.getModifiers())) {
68                return handler.invoke(obj, method, args);
69            }
70
71            // Here I need to check if the fillInStackTrace was called by EasyMock inner code
72            // If it's the case, just ignore the call. We ignore it for two reasons
73            // 1- In Java 7, the fillInStackTrace won't work because, since no constructor was called, the stackTrace attribute is null
74            // 2- There might be some unexpected side effect in the original fillInStackTrace. So it seems more logical to ignore the call
75            if (obj instanceof Throwable && method.getName().equals("fillInStackTrace")) {
76                if(isCallerMockInvocationHandlerInvoke(new Throwable())) {
77                        return obj;
78                }
79            }
80
81            // Bridges should delegate to their bridged method. It should be done before
82            // checking for mocked methods because only unbridged method are mocked
83            // It also make sure the method passed to the handler is not the bridge. Normally it
84            // shouldn't be necessary because bridges are never mocked so are never in the mockedMethods
85            // map. So the normal case is that is will call invokeSuper which will call the interceptor for
86            // the bridged method. The problem is that it doesn't happen. It looks like a cglib bug. For
87            // package scoped bridges (see GenericTest), the interceptor is not called for the bridged
88            // method. Not normal from my point of view.
89            if (method.isBridge()) {
90                method = BridgeMethodResolver.findBridgedMethod(method);
91            }
92
93            if (mockedMethods != null && !mockedMethods.contains(method)) {
94                return proxy.invokeSuper(obj, args);
95            }
96
97            return handler.invoke(obj, method, args);
98        }
99
100        public void setMockedMethods(Method... mockedMethods) {
101            this.mockedMethods = new HashSet<>(Arrays.asList(mockedMethods));
102        }
103
104        @SuppressWarnings("unchecked")
105        private void readObject(java.io.ObjectInputStream stream) throws IOException,
106                ClassNotFoundException {
107            stream.defaultReadObject();
108            Set<MethodSerializationWrapper> methods = (Set<MethodSerializationWrapper>) stream
109                    .readObject();
110            if (methods == null) {
111                return;
112            }
113
114            mockedMethods = new HashSet<>(methods.size());
115            for (MethodSerializationWrapper m : methods) {
116                try {
117                    mockedMethods.add(m.getMethod());
118                } catch (NoSuchMethodException e) {
119                    // ///CLOVER:OFF
120                    throw new IOException(e.toString());
121                    // ///CLOVER:ON
122                }
123            }
124        }
125
126        private void writeObject(java.io.ObjectOutputStream stream) throws IOException {
127            stream.defaultWriteObject();
128
129            if (mockedMethods == null) {
130                stream.writeObject(null);
131                return;
132            }
133
134            Set<MethodSerializationWrapper> methods = new HashSet<>(
135                mockedMethods.size());
136            for (Method m : mockedMethods) {
137                methods.add(new MethodSerializationWrapper(m));
138            }
139
140            stream.writeObject(methods);
141        }
142    }
143
144    // ///CLOVER:OFF (I don't know how to test it automatically yet)
145    private static final NamingPolicy ALLOWS_MOCKING_CLASSES_IN_SIGNED_PACKAGES = new DefaultNamingPolicy() {
146        @Override
147        public String getClassName(String prefix, String source, Object key,
148                Predicate names) {
149            return "codegen." + super.getClassName(prefix, source, key, names);
150        }
151    };
152
153    // ///CLOVER:ON
154
155    public static boolean isCallerMockInvocationHandlerInvoke(Throwable e) {
156        StackTraceElement[] elements = e.getStackTrace();
157        return elements.length > 2
158                && elements[2].getClassName().equals(MockInvocationHandler.class.getName())
159                && elements[2].getMethodName().equals("invoke");
160    }
161
162    @SuppressWarnings("unchecked")
163    public <T> T createProxy(final Class<T> toMock, InvocationHandler handler,
164            Method[] mockedMethods, ConstructorArgs args) {
165        Enhancer enhancer = createEnhancer(toMock);
166
167        MockMethodInterceptor interceptor = new MockMethodInterceptor(handler);
168        if (mockedMethods != null) {
169            interceptor.setMockedMethods(mockedMethods);
170        }
171        enhancer.setCallbackType(interceptor.getClass());
172
173        Class<?> mockClass;
174        try {
175            mockClass = enhancer.createClass();
176        } catch (CodeGenerationException e) {
177            // ///CLOVER:OFF (don't know how to test it automatically)
178            // Probably caused by a NoClassDefFoundError, to use two class loaders at the same time
179            // instead of the default one (which is the class to mock one)
180            // This is required by Eclipse Plug-ins, the mock class loader doesn't see
181            // cglib most of the time. Using EasyMock and the mock class loader at the same time solves this
182            LinkedClassLoader linkedClassLoader = AccessController.doPrivileged((PrivilegedAction<LinkedClassLoader>) () -> new LinkedClassLoader(toMock.getClassLoader(), ClassProxyFactory.class.getClassLoader()));
183            enhancer.setClassLoader(linkedClassLoader);
184            mockClass = enhancer.createClass();
185            // ///CLOVER:ON
186        }
187
188        Factory mock;
189
190        if (args != null) {
191            // Really instantiate the class
192            Constructor<?> cstr;
193            try {
194                // Get the constructor with the same params
195                cstr = mockClass.getDeclaredConstructor(args.getConstructor().getParameterTypes());
196            } catch (NoSuchMethodException e) {
197                // Shouldn't happen, constructor is checked when ConstructorArgs is instantiated
198                // ///CLOVER:OFF
199                throw new RuntimeException("Fail to find constructor for param types", e);
200                // ///CLOVER:ON
201            }
202            try {
203                cstr.setAccessible(true); // So we can call a protected
204                // constructor
205                mock = (Factory) cstr.newInstance(args.getInitArgs());
206            } catch (InstantiationException | IllegalAccessException e) {
207                // ///CLOVER:OFF
208                throw new RuntimeException("Failed to instantiate mock calling constructor", e);
209                // ///CLOVER:ON
210            } catch (InvocationTargetException e) {
211                throw new RuntimeException(
212                        "Failed to instantiate mock calling constructor: Exception in constructor",
213                        e.getTargetException());
214            }
215        } else {
216            // Do not call any constructor
217            try {
218                mock = (Factory) ClassInstantiatorFactory.getInstantiator().newInstance(mockClass);
219            } catch (InstantiationException e) {
220                // ///CLOVER:OFF
221                throw new RuntimeException("Fail to instantiate mock for " + toMock + " on "
222                        + ClassInstantiatorFactory.getJVM() + " JVM");
223                // ///CLOVER:ON
224            }
225        }
226
227        mock.setCallback(0, interceptor);
228        return (T) mock;
229    }
230
231    private Enhancer createEnhancer(Class<?> toMock) {
232        // Create the mock
233        Enhancer enhancer = new Enhancer() {
234
235            /**
236             * Filter all private constructors but do not check that there are
237             * some left
238             */
239            @SuppressWarnings("rawtypes")
240            @Override
241            protected void filterConstructors(Class sc, List constructors) {
242                CollectionUtils.filter(constructors, new VisibilityPredicate(sc, true));
243            }
244        };
245        enhancer.setSuperclass(toMock);
246
247        // ///CLOVER:OFF (I don't know how to test it automatically yet)
248        // See issue ID: 2994002
249        if (toMock.getSigners() != null) {
250            enhancer.setNamingPolicy(ALLOWS_MOCKING_CLASSES_IN_SIGNED_PACKAGES);
251        }
252        // ///CLOVER:ON
253
254        return enhancer;
255    }
256
257    public InvocationHandler getInvocationHandler(Object mock) {
258        Factory factory = (Factory) mock;
259        return ((MockMethodInterceptor) factory.getCallback(0)).handler;
260    }
261}
262
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Trigger code on LambdaTest Cloud Grid

Execute automation tests with on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)