How to use ThreadLocal.withInitial method of org.mockito.internal.creation.bytebuddy.InlineDelegateByteBuddyMockMaker class

Best Mockito code snippet using org.mockito.internal.creation.bytebuddy.InlineDelegateByteBuddyMockMaker.ThreadLocal.withInitial

Source:InlineDelegateByteBuddyMockMaker.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.agent.ByteBuddyAgent;7import org.mockito.MockedConstruction;8import org.mockito.creation.instance.InstantiationException;9import org.mockito.creation.instance.Instantiator;10import org.mockito.exceptions.base.MockitoException;11import org.mockito.exceptions.base.MockitoInitializationException;12import org.mockito.exceptions.misusing.MockitoConfigurationException;13import org.mockito.internal.SuppressSignatureCheck;14import org.mockito.internal.configuration.plugins.Plugins;15import org.mockito.internal.creation.instance.ConstructorInstantiator;16import org.mockito.internal.util.Platform;17import org.mockito.internal.util.concurrent.DetachedThreadLocal;18import org.mockito.internal.util.concurrent.WeakConcurrentMap;19import org.mockito.invocation.MockHandler;20import org.mockito.mock.MockCreationSettings;21import org.mockito.plugins.InlineMockMaker;22import org.mockito.plugins.MemberAccessor;23import java.io.File;24import java.io.FileOutputStream;25import java.io.IOException;26import java.io.InputStream;27import java.lang.instrument.Instrumentation;28import java.lang.reflect.Constructor;29import java.lang.reflect.Modifier;30import java.util.*;31import java.util.concurrent.ConcurrentHashMap;32import java.util.function.BiConsumer;33import java.util.function.Function;34import java.util.function.Predicate;35import java.util.jar.JarEntry;36import java.util.jar.JarFile;37import java.util.jar.JarOutputStream;38import static org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.EXCLUDES;39import static org.mockito.internal.util.StringUtil.join;40/**41 * Agent and subclass based mock maker.42 * <p>43 * This mock maker which uses a combination of the Java instrumentation API and sub-classing rather than creating44 * a new sub-class to create a mock. This way, it becomes possible to mock final types and methods. This mock45 * maker <strong>must to be activated explicitly</strong> for supporting mocking final types and methods:46 * <p>47 * <p>48 * This mock maker can be activated by creating the file <code>/mockito-extensions/org.mockito.plugins.MockMaker</code>49 * containing the text <code>mock-maker-inline</code> or <code>org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker</code>.50 * <p>51 * <p>52 * This mock maker will make a best effort to avoid subclass creation when creating a mock. Otherwise it will use the53 * <code>org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker</code> to create the mock class. That means54 * that the following condition is true55 * <p>56 * <pre class="code"><code class="java">57 * class Foo { }58 * assert mock(Foo.class).getClass() == Foo.class;59 * </pre></code>60 * <p>61 * unless any of the following conditions is met, in such case the mock maker <em>fall backs</em> to the62 * the creation of a subclass.63 * <p>64 * <ul>65 * <li>the type to mock is an abstract class.</li>66 * <li>the mock is set to require additional interfaces.</li>67 * <li>the mock is <a href="#20">explicitly set to support serialization</a>.</li>68 * </ul>69 * <p>70 * <p>71 * Some type of the JDK cannot be mocked, this includes <code>Class</code>, <code>String</code>, and wrapper types.72 * <p>73 * <p>74 * Nevertheless, final methods of such types are mocked when using the inlining mock maker. Mocking final types and enums75 * does however remain impossible when explicitly requiring serialization support or when adding ancillary interfaces.76 * <p>77 * <p>78 * Important behavioral changes when using inline-mocks:79 * <ul>80 * <li>Mockito is capable of mocking package-private methods even if they are defined in different packages than81 * the mocked type. Mockito voluntarily never mocks package-visible methods within <code>java.*</code> packages.</li>82 * <li>Additionally to final types, Mockito can now mock types that are not visible for extension; such types83 * include private types in a protected package.</li>84 * <li>Mockito can no longer mock <code>native</code> methods. Inline mocks require byte code manipulation of a85 * method where native methods do not offer any byte code to manipulate.</li>86 * <li>Mockito cannot longer strip <code>synchronized</code> modifiers from mocked instances.</li>87 * </ul>88 * <p>89 * <p>90 * Note that inline mocks require a Java agent to be attached. Mockito will attempt an attachment of a Java agent upon91 * loading the mock maker for creating inline mocks. Such runtime attachment is only possible when using a JVM that92 * 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 to93 * manually add the <a href="https://bytebuddy.net">Byte Buddy Java agent jar</a> using the <code>-javaagent</code>94 * parameter upon starting the JVM. Furthermore, the inlining mock maker requires the VM to support class retransformation95 * (also known as HotSwap). All major VM distributions such as HotSpot (OpenJDK), J9 (IBM/Websphere) or Zing (Azul)96 * support this feature.97 */98@SuppressSignatureCheck99class InlineDelegateByteBuddyMockMaker100 implements ClassCreatingMockMaker, InlineMockMaker, Instantiator {101 private static final Instrumentation INSTRUMENTATION;102 private static final Throwable INITIALIZATION_ERROR;103 static {104 Instrumentation instrumentation;105 Throwable initializationError = null;106 try {107 try {108 instrumentation = ByteBuddyAgent.install();109 if (!instrumentation.isRetransformClassesSupported()) {110 throw new IllegalStateException(111 join(112 "Byte Buddy requires retransformation for creating inline mocks. This feature is unavailable on the current VM.",113 "",114 "You cannot use this mock maker on this VM"));115 }116 File boot = File.createTempFile("mockitoboot", ".jar");117 boot.deleteOnExit();118 JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(boot));119 try {120 String source =121 "org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher";122 InputStream inputStream =123 InlineDelegateByteBuddyMockMaker.class124 .getClassLoader()125 .getResourceAsStream(source + ".raw");126 if (inputStream == null) {127 throw new IllegalStateException(128 join(129 "The MockMethodDispatcher class file is not locatable: "130 + source131 + ".raw",132 "",133 "The class loader responsible for looking up the resource: "134 + InlineDelegateByteBuddyMockMaker.class135 .getClassLoader()));136 }137 outputStream.putNextEntry(new JarEntry(source + ".class"));138 try {139 int length;140 byte[] buffer = new byte[1024];141 while ((length = inputStream.read(buffer)) != -1) {142 outputStream.write(buffer, 0, length);143 }144 } finally {145 inputStream.close();146 }147 outputStream.closeEntry();148 } finally {149 outputStream.close();150 }151 try (JarFile jarfile = new JarFile(boot)) {152 instrumentation.appendToBootstrapClassLoaderSearch(jarfile);153 }154 try {155 Class.forName(156 "org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher",157 false,158 null);159 } catch (ClassNotFoundException cnfe) {160 throw new IllegalStateException(161 join(162 "Mockito failed to inject the MockMethodDispatcher class into the bootstrap class loader",163 "",164 "It seems like your current VM does not support the instrumentation API correctly."),165 cnfe);166 }167 } catch (IOException ioe) {168 throw new IllegalStateException(169 join(170 "Mockito could not self-attach a Java agent to the current VM. This feature is required for inline mocking.",171 "This error occured due to an I/O error during the creation of this agent: "172 + ioe,173 "",174 "Potentially, the current VM does not support the instrumentation API correctly"),175 ioe);176 }177 } catch (Throwable throwable) {178 instrumentation = null;179 initializationError = throwable;180 }181 INSTRUMENTATION = instrumentation;182 INITIALIZATION_ERROR = initializationError;183 }184 private final BytecodeGenerator bytecodeGenerator;185 private final WeakConcurrentMap<Object, MockMethodInterceptor> mocks =186 new WeakConcurrentMap.WithInlinedExpunction<Object, MockMethodInterceptor>();187 private final DetachedThreadLocal<Map<Class<?>, MockMethodInterceptor>> mockedStatics =188 new DetachedThreadLocal<>(DetachedThreadLocal.Cleaner.INLINE);189 private final DetachedThreadLocal<Map<Class<?>, BiConsumer<Object, MockedConstruction.Context>>>190 mockedConstruction = new DetachedThreadLocal<>(DetachedThreadLocal.Cleaner.INLINE);191 private final ThreadLocal<Boolean> mockitoConstruction = ThreadLocal.withInitial(() -> false);192 private final ThreadLocal<Object> currentSpied = new ThreadLocal<>();193 InlineDelegateByteBuddyMockMaker() {194 if (INITIALIZATION_ERROR != null) {195 String detail;196 if (System.getProperty("java.specification.vendor", "")197 .toLowerCase()198 .contains("android")) {199 detail =200 "It appears as if you are trying to run this mock maker on Android which does not support the instrumentation API.";201 } else {202 try {203 if (INITIALIZATION_ERROR instanceof NoClassDefFoundError204 && INITIALIZATION_ERROR.getMessage() != null205 && INITIALIZATION_ERROR206 .getMessage()207 .startsWith("net/bytebuddy/agent/")) {208 detail =209 join(210 "It seems like you are running Mockito with an incomplete or inconsistent class path. Byte Buddy Agent could not be loaded.",211 "",212 "Byte Buddy Agent is available on Maven Central as 'net.bytebuddy:byte-buddy-agent' with the module name 'net.bytebuddy.agent'.",213 "Normally, your IDE or build tool (such as Maven or Gradle) should take care of your class path completion but ");214 } else if (Class.forName("javax.tools.ToolProvider")215 .getMethod("getSystemJavaCompiler")216 .invoke(null)217 == null) {218 detail =219 "It appears as if you are running on a JRE. Either install a JDK or add JNA to the class path.";220 } else {221 detail =222 "It appears as if your JDK does not supply a working agent attachment mechanism.";223 }224 } catch (Throwable ignored) {225 detail =226 "It appears as if you are running an incomplete JVM installation that might not support all tooling APIs";227 }228 }229 throw new MockitoInitializationException(230 join(231 "Could not initialize inline Byte Buddy mock maker.",232 "",233 detail,234 Platform.describe()),235 INITIALIZATION_ERROR);236 }237 ThreadLocal<Class<?>> currentConstruction = new ThreadLocal<>();238 ThreadLocal<Boolean> isSuspended = ThreadLocal.withInitial(() -> false);239 Predicate<Class<?>> isMockConstruction =240 type -> {241 if (isSuspended.get()) {242 return false;243 } else if (mockitoConstruction.get() || currentConstruction.get() != null) {244 return true;245 }246 Map<Class<?>, ?> interceptors = mockedConstruction.get();247 if (interceptors != null && interceptors.containsKey(type)) {248 currentConstruction.set(type);249 return true;250 } else {251 return false;252 }253 };254 ConstructionCallback onConstruction =255 (type, object, arguments, parameterTypeNames) -> {256 if (mockitoConstruction.get()) {257 Object spy = currentSpied.get();258 if (spy == null) {259 return null;260 } else if (type.isInstance(spy)) {261 return spy;262 } else {263 isSuspended.set(true);264 try {265 // Unexpected construction of non-spied object266 throw new MockitoException(267 "Unexpected spy for "268 + type.getName()269 + " on instance of "270 + object.getClass().getName(),271 object instanceof Throwable ? (Throwable) object : null);272 } finally {273 isSuspended.set(false);274 }275 }276 } else if (currentConstruction.get() != type) {277 return null;278 }279 currentConstruction.remove();280 isSuspended.set(true);281 try {282 Map<Class<?>, BiConsumer<Object, MockedConstruction.Context>> interceptors =283 mockedConstruction.get();284 if (interceptors != null) {285 BiConsumer<Object, MockedConstruction.Context> interceptor =286 interceptors.get(type);287 if (interceptor != null) {288 interceptor.accept(289 object,290 new InlineConstructionMockContext(291 arguments, object.getClass(), parameterTypeNames));292 }293 }294 } finally {295 isSuspended.set(false);296 }297 return null;298 };299 bytecodeGenerator =300 new TypeCachingBytecodeGenerator(301 new InlineBytecodeGenerator(302 INSTRUMENTATION,303 mocks,304 mockedStatics,305 isMockConstruction,306 onConstruction),307 true);308 }309 @Override310 public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {311 return doCreateMock(settings, handler, false);312 }313 @Override314 public <T> Optional<T> createSpy(315 MockCreationSettings<T> settings, MockHandler handler, T object) {316 if (object == null) {317 throw new MockitoConfigurationException("Spy instance must not be null");318 }319 currentSpied.set(object);320 try {321 return Optional.ofNullable(doCreateMock(settings, handler, true));322 } finally {323 currentSpied.remove();324 }325 }326 private <T> T doCreateMock(327 MockCreationSettings<T> settings,328 MockHandler handler,329 boolean nullOnNonInlineConstruction) {330 Class<? extends T> type = createMockType(settings);331 try {332 T instance;333 if (settings.isUsingConstructor()) {334 instance =335 new ConstructorInstantiator(336 settings.getOuterClassInstance() != null,337 settings.getConstructorArgs())338 .newInstance(type);339 } else {340 try {341 // We attempt to use the "native" mock maker first that avoids342 // Objenesis and Unsafe343 instance = newInstance(type);344 } catch (InstantiationException ignored) {345 if (nullOnNonInlineConstruction) {346 return null;347 }348 Instantiator instantiator =349 Plugins.getInstantiatorProvider().getInstantiator(settings);350 instance = instantiator.newInstance(type);351 }352 }353 MockMethodInterceptor mockMethodInterceptor =354 new MockMethodInterceptor(handler, settings);355 mocks.put(instance, mockMethodInterceptor);356 if (instance instanceof MockAccess) {357 ((MockAccess) instance).setMockitoInterceptor(mockMethodInterceptor);358 }359 return instance;360 } catch (InstantiationException e) {361 throw new MockitoException(362 "Unable to create mock instance of type '" + type.getSimpleName() + "'", e);363 }364 }365 @Override366 public <T> Class<? extends T> createMockType(MockCreationSettings<T> settings) {367 try {368 return bytecodeGenerator.mockClass(369 MockFeatures.withMockFeatures(370 settings.getTypeToMock(),371 settings.getExtraInterfaces(),372 settings.getSerializableMode(),373 settings.isStripAnnotations(),374 settings.getDefaultAnswer()));375 } catch (Exception bytecodeGenerationFailed) {376 throw prettifyFailure(settings, bytecodeGenerationFailed);377 }378 }379 private <T> RuntimeException prettifyFailure(380 MockCreationSettings<T> mockFeatures, Exception generationFailed) {381 if (mockFeatures.getTypeToMock().isArray()) {382 throw new MockitoException(383 join("Arrays cannot be mocked: " + mockFeatures.getTypeToMock() + ".", ""),384 generationFailed);385 }386 if (Modifier.isFinal(mockFeatures.getTypeToMock().getModifiers())) {387 throw new MockitoException(388 join(389 "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",390 "Can not mock final classes with the following settings :",391 " - explicit serialization (e.g. withSettings().serializable())",392 " - extra interfaces (e.g. withSettings().extraInterfaces(...))",393 "",394 "You are seeing this disclaimer because Mockito is configured to create inlined mocks.",395 "You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.",396 "",397 "Underlying exception : " + generationFailed),398 generationFailed);399 }400 if (Modifier.isPrivate(mockFeatures.getTypeToMock().getModifiers())) {401 throw new MockitoException(402 join(403 "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",404 "Most likely it is a private class that is not visible by Mockito",405 "",406 "You are seeing this disclaimer because Mockito is configured to create inlined mocks.",407 "You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.",408 ""),409 generationFailed);410 }411 throw new MockitoException(412 join(413 "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",414 "",415 "If you're not sure why you're getting this error, please report to the mailing list.",416 "",417 Platform.warnForVM(418 "IBM J9 VM",419 "Early IBM virtual machine are known to have issues with Mockito, please upgrade to an up-to-date version.\n",420 "Hotspot",421 Platform.isJava8BelowUpdate45()422 ? "Java 8 early builds have bugs that were addressed in Java 1.8.0_45, please update your JDK!\n"423 : ""),424 Platform.describe(),425 "",426 "You are seeing this disclaimer because Mockito is configured to create inlined mocks.",427 "You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.",428 "",429 "Underlying exception : " + generationFailed),430 generationFailed);431 }432 @Override433 public MockHandler getHandler(Object mock) {434 MockMethodInterceptor interceptor;435 if (mock instanceof Class<?>) {436 Map<Class<?>, MockMethodInterceptor> interceptors = mockedStatics.get();437 interceptor = interceptors != null ? interceptors.get(mock) : null;438 } else {439 interceptor = mocks.get(mock);440 }441 if (interceptor == null) {442 return null;443 } else {444 return interceptor.handler;445 }446 }447 @Override448 public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings) {449 MockMethodInterceptor mockMethodInterceptor =450 new MockMethodInterceptor(newHandler, settings);451 if (mock instanceof Class<?>) {452 Map<Class<?>, MockMethodInterceptor> interceptors = mockedStatics.get();453 if (interceptors == null || !interceptors.containsKey(mock)) {454 throw new MockitoException(455 "Cannot reset "456 + mock457 + " which is not currently registered as a static mock");458 }459 interceptors.put((Class<?>) mock, mockMethodInterceptor);460 } else {461 if (!mocks.containsKey(mock)) {462 throw new MockitoException(463 "Cannot reset " + mock + " which is not currently registered as a mock");464 }465 mocks.put(mock, mockMethodInterceptor);466 if (mock instanceof MockAccess) {467 ((MockAccess) mock).setMockitoInterceptor(mockMethodInterceptor);468 }469 }470 }471 @Override472 public void clearAllCaches() {473 clearAllMocks();474 bytecodeGenerator.clearAllCaches();475 }476 @Override477 public void clearMock(Object mock) {478 if (mock instanceof Class<?>) {479 for (Map<Class<?>, ?> entry : mockedStatics.getBackingMap().target.values()) {480 entry.remove(mock);481 }482 } else {483 mocks.remove(mock);484 }485 }486 @Override487 public void clearAllMocks() {488 mockedStatics.getBackingMap().clear();489 mocks.clear();490 }491 @Override492 public TypeMockability isTypeMockable(final Class<?> type) {493 return new TypeMockability() {494 @Override495 public boolean mockable() {496 return INSTRUMENTATION.isModifiableClass(type) && !EXCLUDES.contains(type);497 }498 @Override499 public String nonMockableReason() {500 if (mockable()) {501 return "";502 }503 if (type.isPrimitive()) {504 return "primitive type";505 }506 if (EXCLUDES.contains(type)) {507 return "Cannot mock wrapper types, String.class or Class.class";508 }509 return "VM does not support modification of given type";510 }511 };512 }513 @Override514 public <T> StaticMockControl<T> createStaticMock(515 Class<T> type, MockCreationSettings<T> settings, MockHandler handler) {516 if (type == ConcurrentHashMap.class) {517 throw new MockitoException(518 "It is not possible to mock static methods of ConcurrentHashMap "519 + "to avoid infinitive loops within Mockito's implementation of static mock handling");520 } else if (type == Thread.class521 || type == System.class522 || type == Arrays.class523 || ClassLoader.class.isAssignableFrom(type)) {524 throw new MockitoException(525 "It is not possible to mock static methods of "526 + type.getName()527 + " to avoid interfering with class loading what leads to infinite loops");528 }529 bytecodeGenerator.mockClassStatic(type);530 Map<Class<?>, MockMethodInterceptor> interceptors = mockedStatics.get();531 if (interceptors == null) {532 interceptors = new WeakHashMap<>();533 mockedStatics.set(interceptors);534 }535 return new InlineStaticMockControl<>(type, interceptors, settings, handler);536 }537 @Override538 public <T> ConstructionMockControl<T> createConstructionMock(539 Class<T> type,540 Function<MockedConstruction.Context, MockCreationSettings<T>> settingsFactory,541 Function<MockedConstruction.Context, MockHandler<T>> handlerFactory,542 MockedConstruction.MockInitializer<T> mockInitializer) {543 if (type == Object.class) {544 throw new MockitoException(545 "It is not possible to mock construction of the Object class "546 + "to avoid inference with default object constructor chains");547 } else if (type.isPrimitive() || Modifier.isAbstract(type.getModifiers())) {548 throw new MockitoException(549 "It is not possible to construct primitive types or abstract types: "550 + type.getName());551 }552 bytecodeGenerator.mockClassConstruction(type);553 Map<Class<?>, BiConsumer<Object, MockedConstruction.Context>> interceptors =554 mockedConstruction.get();555 if (interceptors == null) {556 interceptors = new WeakHashMap<>();557 mockedConstruction.set(interceptors);558 }559 return new InlineConstructionMockControl<>(560 type, settingsFactory, handlerFactory, mockInitializer, interceptors);561 }562 @Override563 @SuppressWarnings("unchecked")564 public <T> T newInstance(Class<T> cls) throws InstantiationException {565 Constructor<?>[] constructors = cls.getDeclaredConstructors();566 if (constructors.length == 0) {567 throw new InstantiationException(cls.getName() + " does not define a constructor");568 }569 Constructor<?> selected = constructors[0];570 for (Constructor<?> constructor : constructors) {571 if (Modifier.isPublic(constructor.getModifiers())) {572 selected = constructor;573 break;574 }575 }576 Class<?>[] types = selected.getParameterTypes();577 Object[] arguments = new Object[types.length];578 int index = 0;579 for (Class<?> type : types) {580 arguments[index++] = makeStandardArgument(type);581 }582 MemberAccessor accessor = Plugins.getMemberAccessor();583 try {584 return (T)585 accessor.newInstance(586 selected,587 callback -> {588 mockitoConstruction.set(true);589 try {590 return callback.newInstance();591 } finally {592 mockitoConstruction.set(false);593 }594 },595 arguments);596 } catch (Exception e) {597 throw new InstantiationException("Could not instantiate " + cls.getName(), e);598 }599 }600 private Object makeStandardArgument(Class<?> type) {601 if (type == boolean.class) {602 return false;603 } else if (type == byte.class) {604 return (byte) 0;605 } else if (type == short.class) {606 return (short) 0;607 } else if (type == char.class) {608 return (char) 0;609 } else if (type == int.class) {610 return 0;611 } else if (type == long.class) {612 return 0L;613 } else if (type == float.class) {614 return 0f;615 } else if (type == double.class) {616 return 0d;617 } else {618 return null;619 }620 }621 private static class InlineStaticMockControl<T> implements StaticMockControl<T> {622 private final Class<T> type;623 private final Map<Class<?>, MockMethodInterceptor> interceptors;624 private final MockCreationSettings<T> settings;625 private final MockHandler handler;626 private InlineStaticMockControl(627 Class<T> type,628 Map<Class<?>, MockMethodInterceptor> interceptors,629 MockCreationSettings<T> settings,630 MockHandler handler) {631 this.type = type;632 this.interceptors = interceptors;633 this.settings = settings;634 this.handler = handler;635 }636 @Override637 public Class<T> getType() {638 return type;639 }640 @Override641 public void enable() {642 if (interceptors.putIfAbsent(type, new MockMethodInterceptor(handler, settings))643 != null) {644 throw new MockitoException(645 join(646 "For "647 + type.getName()648 + ", static mocking is already registered in the current thread",649 "",650 "To create a new mock, the existing static mock registration must be deregistered"));651 }652 }653 @Override654 public void disable() {655 if (interceptors.remove(type) == null) {656 throw new MockitoException(657 join(658 "Could not deregister "659 + type.getName()660 + " as a static mock since it is not currently registered",661 "",662 "To register a static mock, use Mockito.mockStatic("663 + type.getSimpleName()664 + ".class)"));665 }666 }667 }668 private class InlineConstructionMockControl<T> implements ConstructionMockControl<T> {669 private final Class<T> type;670 private final Function<MockedConstruction.Context, MockCreationSettings<T>> settingsFactory;671 private final Function<MockedConstruction.Context, MockHandler<T>> handlerFactory;672 private final MockedConstruction.MockInitializer<T> mockInitializer;673 private final Map<Class<?>, BiConsumer<Object, MockedConstruction.Context>> interceptors;674 private final List<Object> all = new ArrayList<>();675 private int count;676 private InlineConstructionMockControl(677 Class<T> type,678 Function<MockedConstruction.Context, MockCreationSettings<T>> settingsFactory,679 Function<MockedConstruction.Context, MockHandler<T>> handlerFactory,680 MockedConstruction.MockInitializer<T> mockInitializer,681 Map<Class<?>, BiConsumer<Object, MockedConstruction.Context>> interceptors) {682 this.type = type;683 this.settingsFactory = settingsFactory;684 this.handlerFactory = handlerFactory;685 this.mockInitializer = mockInitializer;686 this.interceptors = interceptors;687 }688 @Override689 public Class<T> getType() {690 return type;691 }692 @Override693 public void enable() {694 if (interceptors.putIfAbsent(695 type,696 (object, context) -> {697 ((InlineConstructionMockContext) context).count = ++count;698 MockMethodInterceptor interceptor =699 new MockMethodInterceptor(700 handlerFactory.apply(context),701 settingsFactory.apply(context));702 mocks.put(object, interceptor);703 try {704 @SuppressWarnings("unchecked")705 T cast = (T) object;706 mockInitializer.prepare(cast, context);707 } catch (Throwable t) {708 mocks.remove(object); // TODO: filter stack trace?709 throw new MockitoException(710 "Could not initialize mocked construction", t);711 }712 all.add(object);713 })714 != null) {715 throw new MockitoException(716 join(717 "For "718 + type.getName()719 + ", static mocking is already registered in the current thread",720 "",721 "To create a new mock, the existing static mock registration must be deregistered"));722 }723 }724 @Override725 public void disable() {726 if (interceptors.remove(type) == null) {727 throw new MockitoException(728 join(729 "Could not deregister "730 + type.getName()731 + " as a static mock since it is not currently registered",732 "",733 "To register a static mock, use Mockito.mockStatic("734 + type.getSimpleName()735 + ".class)"));736 }737 all.clear();738 }739 @Override740 @SuppressWarnings("unchecked")741 public List<T> getMocks() {742 return (List<T>) all;743 }744 }745 private static class InlineConstructionMockContext implements MockedConstruction.Context {746 private static final Map<String, Class<?>> PRIMITIVES = new HashMap<>();747 static {748 PRIMITIVES.put(boolean.class.getName(), boolean.class);749 PRIMITIVES.put(byte.class.getName(), byte.class);750 PRIMITIVES.put(short.class.getName(), short.class);751 PRIMITIVES.put(char.class.getName(), char.class);752 PRIMITIVES.put(int.class.getName(), int.class);753 PRIMITIVES.put(long.class.getName(), long.class);754 PRIMITIVES.put(float.class.getName(), float.class);755 PRIMITIVES.put(double.class.getName(), double.class);756 }757 private int count;758 private final Object[] arguments;759 private final Class<?> type;760 private final String[] parameterTypeNames;761 private InlineConstructionMockContext(762 Object[] arguments, Class<?> type, String[] parameterTypeNames) {763 this.arguments = arguments;764 this.type = type;765 this.parameterTypeNames = parameterTypeNames;766 }767 @Override768 public int getCount() {769 if (count == 0) {770 throw new MockitoConfigurationException(771 "mocked construction context is not initialized");772 }773 return count;774 }775 @Override776 public Constructor<?> constructor() {777 Class<?>[] parameterTypes = new Class<?>[parameterTypeNames.length];778 int index = 0;779 for (String parameterTypeName : parameterTypeNames) {780 if (PRIMITIVES.containsKey(parameterTypeName)) {781 parameterTypes[index++] = PRIMITIVES.get(parameterTypeName);782 } else {783 try {784 parameterTypes[index++] =785 Class.forName(parameterTypeName, false, type.getClassLoader());786 } catch (ClassNotFoundException e) {787 throw new MockitoException(788 "Could not find parameter of type " + parameterTypeName, e);789 }790 }791 }792 try {793 return type.getDeclaredConstructor(parameterTypes);794 } catch (NoSuchMethodException e) {795 throw new MockitoException(796 join(797 "Could not resolve constructor of type",798 "",799 type.getName(),800 "",801 "with arguments of types",802 Arrays.toString(parameterTypes)),803 e);804 }805 }806 @Override807 public List<?> arguments() {808 return Collections.unmodifiableList(Arrays.asList(arguments));809 }810 }811}...

Full Screen

Full Screen

ThreadLocal.withInitial

Using AI Code Generation

copy

Full Screen

1package com.example.demo;2import org.junit.jupiter.api.Test;3import rg.mokito.Mockito;4import jva.uti.Collections;5importjaa.util.List;6import static org.junit.jupiter.pi.Assetions.assertEquals;7publc clss MockitoInlineDelegateByteBuddyMockMakerTest {8 pulic void test() {9 List mock = Mockito.mock(List.class, Mockito.withSettings().defautAnswr(MockitoCALLS_REAL_METHODS));10 assertEquals(Collections.emptyList(), mock);11 }12}

Full Screen

Full Screen

ThreadLocal.withInitial

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2import java.util.concurrent.atomic.AtomicInteger;3public class Main {4 public static void main(String[] args) {5 AtomicInteger counter = new AtomicInteger(0);6 MyInterface mock = Mockito.mock(MyInterface.class, Mockito.withSettings().defaultAnswer(invocation -> {7 return counter.incrementAndGet();8 }));9 System.out.println(mock.foo());10 System.out.println(mock.foo());11 System.out.println(mock.foo());12 }13 public interface MyInterface {14 int foo();15 }16}

Full Screen

Full Screen

ThreadLocal.withInitial

Using AI Code Generation

copy

Full Screen

1package com.example.demo;2import org.junit.jupiter.api.Test;3import org.mockito.Mockito;4import java.util.Collections;5import java.util.List;6import static org.junit.jupiter.api.Assertions.assertEquals;7public class MockitoInlineDelegateByteBuddyMockMakerTest {8 public void test() {9 List mock = Mockito.mock(List.class, Mockito.withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS));10 assertEquals(Collections.emptyList(), mock);11 }12}

Full Screen

Full Screen

ThreadLocal.withInitial

Using AI Code Generation

copy

Full Screen

1public class ThreadLocalInitialTest {2 private static final ThreadLocal<String> threadLocal = ThreadLocal.withInitial(() -> "test");3 public void test() {4 String value = threadLocal.get();5 System.out.println(value);6 }7}8public class ThreadLocalGetTest {9 private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();10 public void test() {11 String value = threadLocal.get();12 System.out.println(value);13 }

Full Screen

Full Screen

ThreadLocal.withInitial

Using AI Code Generation

copy

Full Screen

1public class ThreadLocalSetTest {2 private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();3 public void test() {4 threadLocal.set("test");5 String value = threadLocal.get();6 System.out.println(value);7 }8}9public class ThreadLocalRemoveTest {10 private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();11 public void test() {12 threadLocal.set("test");13 threadLocal.remove();14 String value = threadLocal.get();15 System.out.println(value);16 }17}18public class ThreadLocalHashCodeTest {19 private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();20 public void test() {21 int hashCode = threadLocal.hashCode();22 System.out.println(hashCode);23 }24}25public class ThreadLocalEqualsTest {26 private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();27 public void test() {28 boolean equals = threadLocal.equals(threadLocal);

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