How to use MethodGraph.Compiler.Default.forJavaHierarchy method of org.mockito.internal.creation.bytebuddy.MockMethodAdvice class

Best Mockito code snippet using org.mockito.internal.creation.bytebuddy.MockMethodAdvice.MethodGraph.Compiler.Default.forJavaHierarchy

Source:MockMethodAdvice.java Github

copy

Full Screen

1/*2 * Copyright (c) 2016 Mockito contributors3 * This program is made available under the terms of the MIT License.4 */5package org.mockito.internal.creation.bytebuddy;6import net.bytebuddy.asm.Advice;7import net.bytebuddy.description.method.MethodDescription;8import net.bytebuddy.description.type.TypeDescription;9import net.bytebuddy.dynamic.scaffold.MethodGraph;10import net.bytebuddy.implementation.bind.annotation.Argument;11import net.bytebuddy.implementation.bind.annotation.This;12import net.bytebuddy.implementation.bytecode.assign.Assigner;13import org.mockito.exceptions.base.MockitoException;14import org.mockito.internal.debugging.LocationImpl;15import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter;16import org.mockito.internal.invocation.RealMethod;17import org.mockito.internal.invocation.SerializableMethod;18import org.mockito.internal.util.concurrent.WeakConcurrentMap;19import java.io.IOException;20import java.io.ObjectInputStream;21import java.io.Serializable;22import java.lang.annotation.Retention;23import java.lang.annotation.RetentionPolicy;24import java.lang.ref.SoftReference;25import java.lang.reflect.InvocationTargetException;26import java.lang.reflect.Method;27import java.lang.reflect.Modifier;28import java.util.ArrayList;29import java.util.List;30import java.util.concurrent.Callable;31public class MockMethodAdvice extends MockMethodDispatcher {32 final WeakConcurrentMap<Object, MockMethodInterceptor> interceptors;33 private final String identifier;34 private final SelfCallInfo selfCallInfo = new SelfCallInfo();35 private final MethodGraph.Compiler compiler = MethodGraph.Compiler.Default.forJavaHierarchy();36 private final WeakConcurrentMap<Class<?>, SoftReference<MethodGraph>> graphs37 = new WeakConcurrentMap.WithInlinedExpunction<Class<?>, SoftReference<MethodGraph>>();38 public MockMethodAdvice(WeakConcurrentMap<Object, MockMethodInterceptor> interceptors, String identifier) {39 this.interceptors = interceptors;40 this.identifier = identifier;41 }42 @SuppressWarnings("unused")43 @Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class)44 private static Callable<?> enter(@Identifier String identifier,45 @Advice.This Object mock,46 @Advice.Origin Method origin,47 @Advice.AllArguments Object[] arguments) throws Throwable {48 MockMethodDispatcher dispatcher = MockMethodDispatcher.get(identifier, mock);49 if (dispatcher == null || !dispatcher.isMocked(mock) || dispatcher.isOverridden(mock, origin)) {50 return null;51 } else {52 return dispatcher.handle(mock, origin, arguments);53 }54 }55 @SuppressWarnings({"unused", "UnusedAssignment"})56 @Advice.OnMethodExit57 private static void exit(@Advice.Return(readOnly = false, typing = Assigner.Typing.DYNAMIC) Object returned,58 @Advice.Enter Callable<?> mocked) throws Throwable {59 if (mocked != null) {60 returned = mocked.call();61 }62 }63 static Throwable hideRecursiveCall(Throwable throwable, int current, Class<?> targetType) {64 try {65 StackTraceElement[] stack = throwable.getStackTrace();66 int skip = 0;67 StackTraceElement next;68 do {69 next = stack[stack.length - current - ++skip];70 } while (!next.getClassName().equals(targetType.getName()));71 int top = stack.length - current - skip;72 StackTraceElement[] cleared = new StackTraceElement[stack.length - skip];73 System.arraycopy(stack, 0, cleared, 0, top);74 System.arraycopy(stack, top + skip, cleared, top, current);75 throwable.setStackTrace(cleared);76 return throwable;77 } catch (RuntimeException ignored) {78 // This should not happen unless someone instrumented or manipulated exception stack traces.79 return throwable;80 }81 }82 @Override83 public Callable<?> handle(Object instance, Method origin, Object[] arguments) throws Throwable {84 MockMethodInterceptor interceptor = interceptors.get(instance);85 if (interceptor == null) {86 return null;87 }88 RealMethod realMethod;89 if (instance instanceof Serializable) {90 realMethod = new SerializableRealMethodCall(identifier, origin, instance, arguments);91 } else {92 realMethod = new RealMethodCall(selfCallInfo, origin, instance, arguments);93 }94 Throwable t = new Throwable();95 t.setStackTrace(skipInlineMethodElement(t.getStackTrace()));96 return new ReturnValueWrapper(interceptor.doIntercept(instance,97 origin,98 arguments,99 realMethod,100 new LocationImpl(t)));101 }102 @Override103 public boolean isMock(Object instance) {104 // We need to exclude 'interceptors.target' explicitly to avoid a recursive check on whether105 // the map is a mock object what requires reading from the map.106 return instance != interceptors.target && interceptors.containsKey(instance);107 }108 @Override109 public boolean isMocked(Object instance) {110 return selfCallInfo.checkSuperCall(instance) && isMock(instance);111 }112 @Override113 public boolean isOverridden(Object instance, Method origin) {114 SoftReference<MethodGraph> reference = graphs.get(instance.getClass());115 MethodGraph methodGraph = reference == null ? null : reference.get();116 if (methodGraph == null) {117 methodGraph = compiler.compile(new TypeDescription.ForLoadedType(instance.getClass()));118 graphs.put(instance.getClass(), new SoftReference<MethodGraph>(methodGraph));119 }120 MethodGraph.Node node = methodGraph.locate(new MethodDescription.ForLoadedMethod(origin).asSignatureToken());121 return !node.getSort().isResolved() || !node.getRepresentative().asDefined().getDeclaringType().represents(origin.getDeclaringClass());122 }123 private static class RealMethodCall implements RealMethod {124 private final SelfCallInfo selfCallInfo;125 private final Method origin;126 private final Object instance;127 private final Object[] arguments;128 private RealMethodCall(SelfCallInfo selfCallInfo, Method origin, Object instance, Object[] arguments) {129 this.selfCallInfo = selfCallInfo;130 this.origin = origin;131 this.instance = instance;132 this.arguments = arguments;133 }134 @Override135 public boolean isInvokable() {136 return true;137 }138 @Override139 public Object invoke() throws Throwable {140 if (!Modifier.isPublic(origin.getDeclaringClass().getModifiers() & origin.getModifiers())) {141 origin.setAccessible(true);142 }143 selfCallInfo.set(instance);144 return tryInvoke(origin, instance, arguments);145 }146 }147 private static class SerializableRealMethodCall implements RealMethod {148 private final String identifier;149 private final SerializableMethod origin;150 private final Object instance;151 private final Object[] arguments;152 private SerializableRealMethodCall(String identifier, Method origin, Object instance, Object[] arguments) {153 this.origin = new SerializableMethod(origin);154 this.identifier = identifier;155 this.instance = instance;156 this.arguments = arguments;157 }158 @Override159 public boolean isInvokable() {160 return true;161 }162 @Override163 public Object invoke() throws Throwable {164 Method method = origin.getJavaMethod();165 if (!Modifier.isPublic(method.getDeclaringClass().getModifiers() & method.getModifiers())) {166 method.setAccessible(true);167 }168 MockMethodDispatcher mockMethodDispatcher = MockMethodDispatcher.get(identifier, instance);169 if (!(mockMethodDispatcher instanceof MockMethodAdvice)) {170 throw new MockitoException("Unexpected dispatcher for advice-based super call");171 }172 Object previous = ((MockMethodAdvice) mockMethodDispatcher).selfCallInfo.replace(instance);173 try {174 return tryInvoke(method, instance, arguments);175 } finally {176 ((MockMethodAdvice) mockMethodDispatcher).selfCallInfo.set(previous);177 }178 }179 }180 private static Object tryInvoke(Method origin, Object instance, Object[] arguments) throws Throwable {181 try {182 return origin.invoke(instance, arguments);183 } catch (InvocationTargetException exception) {184 Throwable cause = exception.getCause();185 new ConditionalStackTraceFilter().filter(hideRecursiveCall(cause, new Throwable().getStackTrace().length, origin.getDeclaringClass()));186 throw cause;187 }188 }189 // With inline mocking, mocks for concrete classes are not subclassed, so elements of the stubbing methods are not filtered out.190 // Therefore, if the method is inlined, skip the element.191 private static StackTraceElement[] skipInlineMethodElement(StackTraceElement[] elements) {192 List<StackTraceElement> list = new ArrayList<StackTraceElement>(elements.length);193 for (int i = 0; i < elements.length; i++) {194 StackTraceElement element = elements[i];195 list.add(element);196 if (element.getClassName().equals(MockMethodAdvice.class.getName()) && element.getMethodName().equals("handle")) {197 // If the current element is MockMethodAdvice#handle(), the next is assumed to be an inlined method.198 i++;199 }200 }201 return list.toArray(new StackTraceElement[list.size()]);202 }203 private static class ReturnValueWrapper implements Callable<Object> {204 private final Object returned;205 private ReturnValueWrapper(Object returned) {206 this.returned = returned;207 }208 @Override209 public Object call() {210 return returned;211 }212 }213 private static class SelfCallInfo extends ThreadLocal<Object> {214 Object replace(Object value) {215 Object current = get();216 set(value);217 return current;218 }219 boolean checkSuperCall(Object value) {220 if (value == get()) {221 set(null);222 return false;223 } else {224 return true;225 }226 }227 }228 @Retention(RetentionPolicy.RUNTIME)229 @interface Identifier {230 }231 static class ForHashCode {232 @SuppressWarnings("unused")233 @Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class)234 private static boolean enter(@Identifier String id,235 @Advice.This Object self) {236 MockMethodDispatcher dispatcher = MockMethodDispatcher.get(id, self);237 return dispatcher != null && dispatcher.isMock(self);238 }239 @SuppressWarnings({"unused", "UnusedAssignment"})240 @Advice.OnMethodExit241 private static void enter(@Advice.This Object self,242 @Advice.Return(readOnly = false) int hashCode,243 @Advice.Enter boolean skipped) {244 if (skipped) {245 hashCode = System.identityHashCode(self);246 }247 }248 }249 static class ForEquals {250 @SuppressWarnings("unused")251 @Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class)252 private static boolean enter(@Identifier String identifier,253 @Advice.This Object self) {254 MockMethodDispatcher dispatcher = MockMethodDispatcher.get(identifier, self);255 return dispatcher != null && dispatcher.isMock(self);256 }257 @SuppressWarnings({"unused", "UnusedAssignment"})258 @Advice.OnMethodExit259 private static void enter(@Advice.This Object self,260 @Advice.Argument(0) Object other,261 @Advice.Return(readOnly = false) boolean equals,262 @Advice.Enter boolean skipped) {263 if (skipped) {264 equals = self == other;265 }266 }267 }268 public static class ForReadObject {269 @SuppressWarnings("unused")270 public static void doReadObject(@Identifier String identifier,271 @This MockAccess thiz,272 @Argument(0) ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {273 objectInputStream.defaultReadObject();274 MockMethodAdvice mockMethodAdvice = (MockMethodAdvice) MockMethodDispatcher.get(identifier, thiz);275 if (mockMethodAdvice != null) {276 mockMethodAdvice.interceptors.put(thiz, thiz.getMockitoInterceptor());277 }278 }279 }280}...

Full Screen

Full Screen

MethodGraph.Compiler.Default.forJavaHierarchy

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.creation.bytebuddy.MockMethodAdvice;2import org.mockito.internal.creation.bytebuddy.MockMethodAdvice$MockMethodInterceptor;3import org.mockito.internal.creation.bytebuddy.MockMethodAdvice$MockMethodInterceptor$MockMethodAdvice$MockMethodInterceptor;4import org.mockito.internal.creation.bytebuddy.MockMethodAdvice$MockMethodInterceptor$MockMethodAdvice$MockMethodInterceptor$MockMethodAdvice$MockMethodInterceptor;5import org.mockito.internal.creation.bytebuddy.MockMethodAdvice$MockMethodInterceptor$MockMethodAdvice$MockMethodInterceptor$MockMethodAdvice$MockMethodInterceptor$MockMethodAdvice$MockMethodInterceptor;6import org.mockito.internal.c

Full Screen

Full Screen

MethodGraph.Compiler.Default.forJavaHierarchy

Using AI Code Generation

copy

Full Screen

1 public boolean isMockedMethod(Method method) {2 if (method == null) {3 return false;4 }5 List<String> methodNames = new ArrayList<String>();6 Class<?>[] hierarchy = MethodGraph.Compiler.Default.forJavaHierarchy().resolve(method.getDeclaringClass()).getClasses();7 for (Class<?> clazz : hierarchy) {8 for (Method m : clazz.getDeclaredMethods()) {9 if (m.isSynthetic()) {10 continue;11 }12 methodNames.add(m.getName());13 }14 }15 return methodNames.contains(method.getName());16 }17 public static void main(String[] args) {18 System.out.println(new MockitoTest().isMockedMethod(null));19 System.out.println(new MockitoTest().isMockedMethod(new Object() {20 public void method() {21 }22 }.getClass().getDeclaredMethods()[0]));23 }24}25public static boolean isMockedMethod(Method method) {26 if (method == null) {27 return false;28 }29 List<String> methodNames = new ArrayList<String>();30 Class<?>[] hierarchy = MethodGraph.Compiler.Default.forJavaHierarchy().resolve(method.getDeclaringClass()).getClasses();31 for (Class<?> clazz : hierarchy) {32 for (Method m : clazz.getDeclaredMethods()) {33 if (m.isSynthetic()) {34 continue;35 }36 methodNames.add(m.getName());37 }38 }39 return methodNames.contains(method.getName());40}41public static boolean isMockedMethod(Method method) {42 if (method == null) {43 return false;44 }45 List<String> methodNames = new ArrayList<String>();46 Class<?>[] hierarchy = MethodGraph.Compiler.Default.forJavaHierarchy().resolve(method.getDeclaringClass()).getClasses();47 for (Class<?> clazz : hierarchy) {48 for (Method m : clazz.getDeclaredMethods()) {49 if (m.isSynthetic()) {50 continue;51 }

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful