Best Mockito code snippet using org.mockito.internal.creation.bytebuddy.BytecodeGenerator
Source:InlineByteBuddyMockMaker.java
...21import java.lang.reflect.Modifier;22import java.util.jar.JarEntry;23import java.util.jar.JarFile;24import java.util.jar.JarOutputStream;25import static org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.EXCLUDES;26import static org.mockito.internal.util.StringUtil.join;27/**28 * Agent and subclass based mock maker.29 * <p>30 * This mock maker which uses a combination of the Java instrumentation API and sub-classing rather than creating31 * a new sub-class to create a mock. This way, it becomes possible to mock final types and methods. This mock32 * maker <strong>must to be activated explicitly</strong> for supporting mocking final types and methods:33 * <p>34 * <p>35 * This mock maker can be activated by creating the file <code>/mockito-extensions/org.mockito.plugins.MockMaker</code>36 * containing the text <code>mock-maker-inline</code> or <code>org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker</code>.37 * <p>38 * <p>39 * This mock maker will make a best effort to avoid subclass creation when creating a mock. Otherwise it will use the40 * <code>org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker</code> to create the mock class. That means41 * that the following condition is true42 * <p>43 * <pre class="code"><code class="java">44 * class Foo { }45 * assert mock(Foo.class).getClass() == Foo.class;46 * </pre></code>47 * <p>48 * unless any of the following conditions is met, in such case the mock maker <em>fall backs</em> to the49 * the creation of a subclass.50 * <p>51 * <ul>52 * <li>the type to mock is an abstract class.</li>53 * <li>the mock is set to require additional interfaces.</li>54 * <li>the mock is <a href="#20">explicitly set to support serialization</a>.</li>55 * </ul>56 * <p>57 * <p>58 * Some type of the JDK cannot be mocked, this includes <code>Class</code>, <code>String</code>, and wrapper types.59 * <p>60 * <p>61 * Nevertheless, final methods of such types are mocked when using the inlining mock maker. Mocking final types and enums62 * does however remain impossible when explicitly requiring serialization support or when adding ancillary interfaces.63 * <p>64 * <p>65 * Important behavioral changes when using inline-mocks:66 * <ul>67 * <li>Mockito is capable of mocking package-private methods even if they are defined in different packages than68 * the mocked type. Mockito voluntarily never mocks package-visible methods within <code>java.*</code> packages.</li>69 * <li>Additionally to final types, Mockito can now mock types that are not visible for extension; such types70 * include private types in a protected package.</li>71 * <li>Mockito can no longer mock <code>native</code> methods. Inline mocks require byte code manipulation of a72 * method where native methods do not offer any byte code to manipulate.</li>73 * <li>Mockito cannot longer strip <code>synchronized</code> modifiers from mocked instances.</li>74 * </ul>75 * <p>76 * <p>77 * Note that inline mocks require a Java agent to be attached. Mockito will attempt an attachment of a Java agent upon78 * loading the mock maker for creating inline mocks. Such runtime attachment is only possible when using a JVM that79 * is part of a JDK or when using a Java 9 VM. When running on a non-JDK VM prior to Java 9, it is however possible to80 * manually add the <a href="http://bytebuddy.net">Byte Buddy Java agent jar</a> using the <code>-javaagent</code>81 * parameter upon starting the JVM. Furthermore, the inlining mock maker requires the VM to support class retransformation82 * (also known as HotSwap). All major VM distributions such as HotSpot (OpenJDK), J9 (IBM/Websphere) or Zing (Azul)83 * support this feature.84 */85@Incubating86public class InlineByteBuddyMockMaker implements ClassCreatingMockMaker {87 private static final Instrumentation INSTRUMENTATION;88 private static final Throwable INITIALIZATION_ERROR;89 static {90 Instrumentation instrumentation;91 Throwable initializationError = null;92 try {93 try {94 instrumentation = ByteBuddyAgent.install();95 if (!instrumentation.isRetransformClassesSupported()) {96 throw new IllegalStateException(join(97 "Byte Buddy requires retransformation for creating inline mocks. This feature is unavailable on the current VM.",98 "",99 "You cannot use this mock maker on this VM"));100 }101 File boot = File.createTempFile("mockitoboot", ".jar");102 boot.deleteOnExit();103 JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(boot));104 try {105 String source = "org/mockito/internal/creation/bytebuddy/MockMethodDispatcher";106 InputStream inputStream = InlineByteBuddyMockMaker.class.getClassLoader().getResourceAsStream(source + ".raw");107 if (inputStream == null) {108 throw new IllegalStateException(join(109 "The MockMethodDispatcher class file is not locatable: " + source + ".raw",110 "",111 "The class loader responsible for looking up the resource: " + InlineByteBuddyMockMaker.class.getClassLoader()112 ));113 }114 outputStream.putNextEntry(new JarEntry(source + ".class"));115 try {116 int length;117 byte[] buffer = new byte[1024];118 while ((length = inputStream.read(buffer)) != -1) {119 outputStream.write(buffer, 0, length);120 }121 } finally {122 inputStream.close();123 }124 outputStream.closeEntry();125 } finally {126 outputStream.close();127 }128 instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(boot));129 try {130 Class<?> dispatcher = Class.forName("org.mockito.internal.creation.bytebuddy.MockMethodDispatcher");131 if (dispatcher.getClassLoader() != null) {132 throw new IllegalStateException(join(133 "The MockMethodDispatcher must not be loaded manually but must be injected into the bootstrap class loader.",134 "",135 "The dispatcher class was already loaded by: " + dispatcher.getClassLoader()));136 }137 } catch (ClassNotFoundException cnfe) {138 throw new IllegalStateException(join(139 "Mockito failed to inject the MockMethodDispatcher class into the bootstrap class loader",140 "",141 "It seems like your current VM does not support the instrumentation API correctly."), cnfe);142 }143 } catch (IOException ioe) {144 throw new IllegalStateException(join(145 "Mockito could not self-attach a Java agent to the current VM. This feature is required for inline mocking.",146 "This error occured due to an I/O error during the creation of this agent: " + ioe,147 "",148 "Potentially, the current VM does not support the instrumentation API correctly"), ioe);149 }150 } catch (Throwable throwable) {151 instrumentation = null;152 initializationError = throwable;153 }154 INSTRUMENTATION = instrumentation;155 INITIALIZATION_ERROR = initializationError;156 }157 private final BytecodeGenerator bytecodeGenerator;158 private final WeakConcurrentMap<Object, MockMethodInterceptor> mocks = new WeakConcurrentMap.WithInlinedExpunction<Object, MockMethodInterceptor>();159 public InlineByteBuddyMockMaker() {160 if (INITIALIZATION_ERROR != null) {161 throw new MockitoInitializationException(join(162 "Could not initialize inline Byte Buddy mock maker. (This mock maker is not supported on Android.)",163 "",164 Platform.describe()), INITIALIZATION_ERROR);165 }166 bytecodeGenerator = new TypeCachingBytecodeGenerator(new InlineBytecodeGenerator(INSTRUMENTATION, mocks), true);167 }168 @Override169 public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {170 Class<? extends T> type = createMockType(settings);171 Instantiator instantiator = Plugins.getInstantiatorProvider().getInstantiator(settings);172 try {173 T instance = instantiator.newInstance(type);174 MockMethodInterceptor mockMethodInterceptor = new MockMethodInterceptor(handler, settings);175 mocks.put(instance, mockMethodInterceptor);176 if (instance instanceof MockAccess) {177 ((MockAccess) instance).setMockitoInterceptor(mockMethodInterceptor);178 }179 return instance;180 } catch (org.mockito.internal.creation.instance.InstantiationException e) {...
Source:TypeCachingBytecodeGenerator.java
...7import org.mockito.mock.SerializableMode;8import java.lang.ref.ReferenceQueue;9import java.util.Set;10import java.util.concurrent.Callable;11class TypeCachingBytecodeGenerator extends ReferenceQueue<ClassLoader> implements BytecodeGenerator {12 private final Object BOOTSTRAP_LOCK = new Object();13 private final BytecodeGenerator bytecodeGenerator;14 private final TypeCache<MockitoMockKey> typeCache;15 public TypeCachingBytecodeGenerator(BytecodeGenerator bytecodeGenerator, boolean weak) {16 this.bytecodeGenerator = bytecodeGenerator;17 typeCache = new TypeCache.WithInlineExpunction<MockitoMockKey>(weak ? TypeCache.Sort.WEAK : TypeCache.Sort.SOFT);18 }19 @SuppressWarnings("unchecked")20 @Override21 public <T> Class<T> mockClass(final MockFeatures<T> params) {22 try {23 ClassLoader classLoader = params.mockedType.getClassLoader();24 return (Class<T>) typeCache.findOrInsert(classLoader,25 new MockitoMockKey(params.mockedType, params.interfaces, params.serializableMode, params.stripAnnotations),26 new Callable<Class<?>>() {27 @Override28 public Class<?> call() throws Exception {29 return bytecodeGenerator.mockClass(params);...
BytecodeGenerator
Using AI Code Generation
1import net.bytebuddy.ByteBuddy;2import net.bytebuddy.description.method.MethodDescription;3import net.bytebuddy.dynamic.DynamicType;4import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;5import net.bytebuddy.implementation.InvocationHandlerAdapter;6import net.bytebuddy.matcher.ElementMatchers;7import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor;8import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.DispatcherDefaultingToRealMethod;9import java.lang.reflect.Method;10import static net.bytebuddy.matcher.ElementMatchers.any;11public class BytecodeGenerator {12 public static void main(String[] args) throws Exception {13 DynamicType.Builder<?> builder = new ByteBuddy()14 .subclass(Object.class)15 .name("foo.Bar")16 .method(any())17 .intercept(InvocationHandlerAdapter.of(new MockMethodInterceptor(new DispatcherDefaultingToRealMethod())));18 Class<?> dynamicType = builder.make()19 .load(BytecodeGenerator.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)20 .getLoaded();21 Object instance = dynamicType.newInstance();22 Method method = dynamicType.getMethod("toString");23 System.out.println(method.invoke(instance));24 }25}26import net.bytebuddy.ByteBuddy;27import net.bytebuddy.description.method.MethodDescription;28import net.bytebuddy.dynamic.DynamicType;29import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;30import net.bytebuddy.implementation.InvocationHandlerAdapter;31import net.bytebuddy.matcher.ElementMatchers;32import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor;33import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.DispatcherDefaultingToRealMethod;34import java.lang.reflect.Method;35import static net.bytebuddy.matcher.ElementMatchers.any;36public class BytecodeGenerator {37 public static void main(String[] args) throws Exception {38 DynamicType.Builder<?> builder = new ByteBuddy()39 .subclass(Object.class)40 .name("foo.Bar")41 .method(any())42 .intercept(InvocationHandlerAdapter.of(new MockMethodInterceptor(new DispatcherDefaultingToRealMethod())));43 Class<?> dynamicType = builder.make()44 .load(BytecodeGenerator.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)45 .getLoaded();46 Object instance = dynamicType.newInstance();47 Method method = dynamicType.getMethod("toString");48 System.out.println(method.invoke(instance));49 }50}
BytecodeGenerator
Using AI Code Generation
1import org.mockito.internal.creation.bytebuddy.BytecodeGenerator;2import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor;3import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.DispatcherDefaultingToRealMethod;4import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.DispatcherIgnoringStubs;5import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.DispatcherNotifyingMockHandler;6import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.DispatcherSafe;7import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.DispatcherSafeWithStubs;8import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.DispatcherToRealMethod;9import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.DispatcherToRealMethodInSequence;10import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.DispatcherToReturnValues;11import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.DispatcherToThrowException;12import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.Interceptor;13import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.InterceptorSafe;14import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.InterceptorSafeWithStubs;15import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.InterceptorToRealMethod;16import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.InterceptorToRealMethodInSequence;17import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.InterceptorToReturnValues;18import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.InterceptorToThrowException;19import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.SimpleMockMethodInterceptor;20import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.SimpleMockMethodInterceptorWithStubs;21import org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator;22import org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.CacheProvider;23import org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.CachedBytecodeGenerator;24import org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.CachedBytecodeGeneratorWithMockitoClassloader;25import org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.CachingMockitoClassloader;26import org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.DefaultCacheProvider;27import org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.DefaultCacheProvider.BootstrapClassLoaderProvider;28import org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.DefaultCacheProvider.BootstrapClassLoaderProvider.BootstrapClassLoader;29import org.mockito.internal.creation.bytebuddy.TypeCaching
BytecodeGenerator
Using AI Code Generation
1import org.mockito.internal.creation.bytebuddy.BytecodeGenerator;2import org.mockito.internal.creation.bytebuddy.MockAccess;3import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor;4import org.mockito.internal.util.MockUtil;5import org.mockito.invocation.MockHandler;6import org.mockito.mock.MockCreationSettings;7import org.mockito.plugins.MockMaker;8import java.lang.reflect.Constructor;9import java.lang.reflect.InvocationTargetException;10import java.lang.reflect.Method;11import java.lang.reflect.Modifier;12public class ByteBuddyMockMaker implements MockMaker {13 private static final String MOCKITO_MOCKS_PACKAGE = "org.mockito.codegen";14 private final BytecodeGenerator mockBytecodeGenerator = new BytecodeGenerator();15 private final BytecodeGenerator spyBytecodeGenerator = new BytecodeGenerator();16 public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {17 Class<T> mockedType = settings.getTypeToMock();18 ClassLoader classLoader = mockedType.getClassLoader();19 boolean isInterface = mockedType.isInterface();20 String mockName = createMockName(settings);21 Class<?> mockClass = isInterface ? createInterfaceMockClass(mockName, settings) : createClassMockClass(mockName, settings);22 Constructor<?> constructor = findConstructor(mockClass);23 try {24 T mock = (T) constructor.newInstance(handler);25 MockAccess mockAccess = (MockAccess) mock;26 mockAccess.setMockitoInterceptor(new MockMethodInterceptor(handler));27 return mock;28 } catch (InstantiationException e) {29 throw new RuntimeException(e);30 } catch (IllegalAccessException e) {31 throw new RuntimeException(e);32 } catch (InvocationTargetException e) {33 throw new RuntimeException(e);34 }35 }36 private <T> String createMockName(MockCreationSettings<T> settings) {37 String name = MockUtil.getMockName(settings);38 if (name != null) {39 return name;40 }41 Class<T> type = settings.getTypeToMock();42 return type.getSimpleName();43 }44 private <T> Class<?> createClassMockClass(String mockName, MockCreationSettings<T> settings) {45 return mockBytecodeGenerator.mockClass(MOCKITO_MOCKS_PACKAGE, mockName, settings);46 }47 private <T> Class<?> createInterfaceMockClass(String mockName, MockCreationSettings<T> settings) {48 return mockBytecodeGenerator.mockInterface(MOCKITO_MOCKS
BytecodeGenerator
Using AI Code Generation
1public class 1 {2 public static void main(String[] args) {3 System.out.println("mocking a class and calling the method of the mocked class");4 BytecodeGenerator mockBytecodeGenerator = new BytecodeGenerator();5 Class<?> mockClass = mockBytecodeGenerator.mockClass(MockedClass.class);6 MockedClass mock = (MockedClass) mockBytecodeGenerator.mock(mockClass);7 mock.mockedMethod();8 }9}10public class 2 {11 public static void main(String[] args) {12 System.out.println("mocking a class and calling the method of the mocked class");13 ByteBuddyMockMaker mockMaker = new ByteBuddyMockMaker();14 MockedClass mock = (MockedClass) mockMaker.createMock(MockingSettingsImpl.mockSettings(MockedClass.class), new MockCreationValidator());15 mock.mockedMethod();16 }17}18public class 3 {19 public static void main(String[] args) {20 System.out.println("mocking a class and calling the method of the mocked class");21 ByteBuddyMockMaker mockMaker = new ByteBuddyMockMaker();22 MockedClass mock = (MockedClass) mockMaker.createMock(MockingSettings
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!