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

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

Run Easymock automation tests on LambdaTest cloud grid

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

copy
1/**
2 * Copyright 2001-2013 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 java.io.*;
19import java.lang.reflect.*;
20
21import org.easymock.EasyMock;
22
23/**
24 * Default class instantiator that is pretty limited. It just hope that the
25 * mocked class has a public empty constructor.
26 * 
27 * @author Henri Tremblay
28 */
29public class DefaultClassInstantiator implements IClassInstantiator {
30
31    /**
32     * Try to instantiate a class without using a special constructor. See
33     * documentation for the algorithm.
34     * 
35     * @param c
36     *            Class to instantiate
37     */
38    public Object newInstance(final Class<?> c) throws InstantiationException {
39
40        if (isSerializable(c)) {
41            try {
42                return readObject(getSerializedBytes(c));
43                // ///CLOVER:OFF
44            } catch (final IOException e) {
45                throw new RuntimeException("Failed to instantiate " + c.getName() + "'s mock: ", e);
46            } catch (final ClassNotFoundException e) {
47                throw new RuntimeException("Failed to instantiate " + c.getName() + "'s mock: ", e);
48            }
49            // ///CLOVER:ON
50        }
51
52        final Constructor<?> constructor = getConstructorToUse(c);
53        final Object[] params = getArgsForTypes(constructor.getParameterTypes());
54        try {
55            return constructor.newInstance(params);
56            // ///CLOVER:OFF
57        } catch (final IllegalArgumentException e) {
58            throw new RuntimeException("Failed to instantiate " + c.getName() + "'s mock: ", e);
59        } catch (final IllegalAccessException e) {
60            throw new RuntimeException("Failed to instantiate " + c.getName() + "'s mock: ", e);
61            // ///CLOVER:ON
62        } catch (final InvocationTargetException e) {
63            throw new RuntimeException("Failed to instantiate " + c.getName() + "'s mock: ", e);
64        }
65    }
66
67    /**
68     * Tells if the provided class is serializable
69     * 
70     * @param clazz
71     *            Class to check
72     * @return If the class is serializable
73     */
74    private boolean isSerializable(final Class<?> clazz) {
75        return Serializable.class.isAssignableFrom(clazz);
76    }
77
78    /**
79     * Return the constructor considered the best to use with this class.
80     * Algorithm is: No args constructor and then first constructor defined in
81     * the class
82     * 
83     * @param clazz
84     *            Class in which constructor is searched
85     * @return Constructor to use
86     */
87    public Constructor<?> getConstructorToUse(final Class<?> clazz) {
88        // First try to use the empty constructor
89        try {
90            return clazz.getConstructor(new Class[0]);
91        } catch (final NoSuchMethodException e) {
92            // If it fails just use the first one
93            if (clazz.getConstructors().length == 0) {
94                throw new IllegalArgumentException("No visible constructors in class " + clazz.getName());
95            }
96            return clazz.getConstructors()[0];
97        }
98    }
99
100    /**
101     * Get some default instances of provided classes
102     * 
103     * @param methodTypes
104     *            Classes to instantiate
105     * @return Instances of methodTypes in order
106     * @throws InstantiationException Thrown if the class instantiation fails
107     */
108    public Object[] getArgsForTypes(final Class<?>[] methodTypes) throws InstantiationException {
109        final Object[] methodArgs = new Object[methodTypes.length];
110
111        for (int i = 0; i < methodTypes.length; i++) {
112
113            if (methodTypes[i].isPrimitive()) {
114                // Return a nice wrapped primitive type
115                methodArgs[i] = RecordState.emptyReturnValueFor(methodTypes[i]);
116            // ///CLOVER:OFF TODO: Remove when we manage to fix the ignored tests
117            } else if (Modifier.isFinal(methodTypes[i].getModifiers())) {
118                // Instantiate the class using the best constructor we can find
119                // (because it's not
120                // possible to mock a final class)
121                methodArgs[i] = newInstance(methodTypes[i]);
122                // ///CLOVER:ON
123            } else {
124                // For all classes and interfaces, just return a nice mock
125                final Object mock = EasyMock.createNiceMock(methodTypes[i]);
126                EasyMock.replay(mock);
127                methodArgs[i] = mock;
128            }
129        }
130        return methodArgs;
131    }
132
133    private static byte[] getSerializedBytes(final Class<?> clazz) throws IOException {
134        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
135        final DataOutputStream data = new DataOutputStream(baos);
136        data.writeShort(ObjectStreamConstants.STREAM_MAGIC);
137        data.writeShort(ObjectStreamConstants.STREAM_VERSION);
138        data.writeByte(ObjectStreamConstants.TC_OBJECT);
139        data.writeByte(ObjectStreamConstants.TC_CLASSDESC);
140        data.writeUTF(clazz.getName());
141
142        final Long suid = getSerializableUID(clazz);
143
144        data.writeLong(suid.longValue());
145
146        data.writeByte(2); // classDescFlags (2 = Serializable)
147        data.writeShort(0); // field count
148        data.writeByte(ObjectStreamConstants.TC_ENDBLOCKDATA);
149        data.writeByte(ObjectStreamConstants.TC_NULL);
150        return baos.toByteArray();
151    }
152
153    private static Long getSerializableUID(final Class<?> clazz) {
154
155        try {
156            final Field f = clazz.getDeclaredField("serialVersionUID");
157            final int mask = Modifier.STATIC | Modifier.FINAL;
158            if ((f.getModifiers() & mask) == mask) {
159                f.setAccessible(true);
160                return Long.valueOf(f.getLong(null));
161            }
162        } catch (final NoSuchFieldException e) {
163            // It's not there, compute it then
164        } catch (final IllegalAccessException e) {
165            // ///CLOVER:OFF
166            throw new RuntimeException("Should have been able to get serialVersionUID since it's there");
167            // ///CLOVER:ON
168        }
169        // ///CLOVER:OFF
170        return callLongMethod(clazz,
171                ClassInstantiatorFactory.is1_3Specifications() ? "computeSerialVersionUID"
172                        : "computeDefaultSUID");
173        // ///CLOVER:ON
174    }
175
176    private static Long callLongMethod(final Class<?> clazz, final String methodName) {
177
178        Method method;
179        // ///CLOVER:OFF
180        try {
181            method = ObjectStreamClass.class.getDeclaredMethod(methodName, new Class[] { Class.class });
182        } catch (final NoSuchMethodException e) {
183            throw new InternalError("ObjectStreamClass." + methodName + " seems to have vanished");
184        }
185        final boolean accessible = method.isAccessible();
186        method.setAccessible(true);
187        Long suid;
188        try {
189            suid = (Long) method.invoke(null, new Object[] { clazz });
190        } catch (final IllegalAccessException e) {
191            throw new InternalError("ObjectStreamClass." + methodName + " should have been accessible");
192        } catch (final InvocationTargetException e) {
193            throw new InternalError("ObjectStreamClass." + methodName + " failled to be called: "
194                    + e.getMessage());
195        }
196        method.setAccessible(accessible);
197        // ///CLOVER:ON
198        return suid;
199    }
200
201    private static Object readObject(final byte[] bytes) throws IOException, ClassNotFoundException {
202        final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
203        return in.readObject();
204    }
205
206}
207
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)