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

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

Source:InlineDelegateByteBuddyMockMaker.java Github

copy

Full Screen

...288 interceptors.get(type);289 if (interceptor != null) {290 interceptor.accept(291 object,292 new InlineConstructionMockContext(293 arguments, object.getClass(), parameterTypeNames));294 }295 }296 } finally {297 isSuspended.set(false);298 }299 return null;300 };301 bytecodeGenerator =302 new TypeCachingBytecodeGenerator(303 new InlineBytecodeGenerator(304 INSTRUMENTATION,305 mocks,306 mockedStatics,307 isMockConstruction,308 onConstruction),309 true);310 }311 @Override312 public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {313 return doCreateMock(settings, handler, false);314 }315 @Override316 public <T> Optional<T> createSpy(317 MockCreationSettings<T> settings, MockHandler handler, T object) {318 if (object == null) {319 throw new MockitoConfigurationException("Spy instance must not be null");320 }321 currentSpied.set(object);322 try {323 return Optional.ofNullable(doCreateMock(settings, handler, true));324 } finally {325 currentSpied.remove();326 }327 }328 private <T> T doCreateMock(329 MockCreationSettings<T> settings,330 MockHandler handler,331 boolean nullOnNonInlineConstruction) {332 Class<? extends T> type = createMockType(settings);333 try {334 T instance;335 if (settings.isUsingConstructor()) {336 instance =337 new ConstructorInstantiator(338 settings.getOuterClassInstance() != null,339 settings.getConstructorArgs())340 .newInstance(type);341 } else {342 try {343 // We attempt to use the "native" mock maker first that avoids344 // Objenesis and Unsafe345 instance = newInstance(type);346 } catch (InstantiationException ignored) {347 if (nullOnNonInlineConstruction) {348 return null;349 }350 Instantiator instantiator =351 Plugins.getInstantiatorProvider().getInstantiator(settings);352 instance = instantiator.newInstance(type);353 }354 }355 MockMethodInterceptor mockMethodInterceptor =356 new MockMethodInterceptor(handler, settings);357 mocks.put(instance, mockMethodInterceptor);358 if (instance instanceof MockAccess) {359 ((MockAccess) instance).setMockitoInterceptor(mockMethodInterceptor);360 }361 return instance;362 } catch (InstantiationException e) {363 throw new MockitoException(364 "Unable to create mock instance of type '" + type.getSimpleName() + "'", e);365 }366 }367 @Override368 public <T> Class<? extends T> createMockType(MockCreationSettings<T> settings) {369 try {370 return bytecodeGenerator.mockClass(371 MockFeatures.withMockFeatures(372 settings.getTypeToMock(),373 settings.getExtraInterfaces(),374 settings.getSerializableMode(),375 settings.isStripAnnotations()));376 } catch (Exception bytecodeGenerationFailed) {377 throw prettifyFailure(settings, bytecodeGenerationFailed);378 }379 }380 private <T> RuntimeException prettifyFailure(381 MockCreationSettings<T> mockFeatures, Exception generationFailed) {382 if (mockFeatures.getTypeToMock().isArray()) {383 throw new MockitoException(384 join("Arrays cannot be mocked: " + mockFeatures.getTypeToMock() + ".", ""),385 generationFailed);386 }387 if (Modifier.isFinal(mockFeatures.getTypeToMock().getModifiers())) {388 throw new MockitoException(389 join(390 "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",391 "Can not mock final classes with the following settings :",392 " - explicit serialization (e.g. withSettings().serializable())",393 " - extra interfaces (e.g. withSettings().extraInterfaces(...))",394 "",395 "You are seeing this disclaimer because Mockito is configured to create inlined mocks.",396 "You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.",397 "",398 "Underlying exception : " + generationFailed),399 generationFailed);400 }401 if (Modifier.isPrivate(mockFeatures.getTypeToMock().getModifiers())) {402 throw new MockitoException(403 join(404 "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",405 "Most likely it is a private class that is not visible by Mockito",406 "",407 "You are seeing this disclaimer because Mockito is configured to create inlined mocks.",408 "You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.",409 ""),410 generationFailed);411 }412 throw new MockitoException(413 join(414 "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",415 "",416 "If you're not sure why you're getting this error, please report to the mailing list.",417 "",418 Platform.warnForVM(419 "IBM J9 VM",420 "Early IBM virtual machine are known to have issues with Mockito, please upgrade to an up-to-date version.\n",421 "Hotspot",422 Platform.isJava8BelowUpdate45()423 ? "Java 8 early builds have bugs that were addressed in Java 1.8.0_45, please update your JDK!\n"424 : ""),425 Platform.describe(),426 "",427 "You are seeing this disclaimer because Mockito is configured to create inlined mocks.",428 "You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.",429 "",430 "Underlying exception : " + generationFailed),431 generationFailed);432 }433 @Override434 public MockHandler getHandler(Object mock) {435 MockMethodInterceptor interceptor;436 if (mock instanceof Class<?>) {437 Map<Class<?>, MockMethodInterceptor> interceptors = mockedStatics.get();438 interceptor = interceptors != null ? interceptors.get(mock) : null;439 } else {440 interceptor = mocks.get(mock);441 }442 if (interceptor == null) {443 return null;444 } else {445 return interceptor.handler;446 }447 }448 @Override449 public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings) {450 MockMethodInterceptor mockMethodInterceptor =451 new MockMethodInterceptor(newHandler, settings);452 if (mock instanceof Class<?>) {453 Map<Class<?>, MockMethodInterceptor> interceptors = mockedStatics.get();454 if (interceptors == null || !interceptors.containsKey(mock)) {455 throw new MockitoException(456 "Cannot reset "457 + mock458 + " which is not currently registered as a static mock");459 }460 interceptors.put((Class<?>) mock, mockMethodInterceptor);461 } else {462 if (!mocks.containsKey(mock)) {463 throw new MockitoException(464 "Cannot reset " + mock + " which is not currently registered as a mock");465 }466 mocks.put(mock, mockMethodInterceptor);467 if (mock instanceof MockAccess) {468 ((MockAccess) mock).setMockitoInterceptor(mockMethodInterceptor);469 }470 }471 }472 @Override473 public void clearAllCaches() {474 clearAllMocks();475 bytecodeGenerator.clearAllCaches();476 }477 @Override478 public void clearMock(Object mock) {479 if (mock instanceof Class<?>) {480 for (Map<Class<?>, ?> entry : mockedStatics.getBackingMap().target.values()) {481 entry.remove(mock);482 }483 } else {484 mocks.remove(mock);485 }486 }487 @Override488 public void clearAllMocks() {489 mockedStatics.getBackingMap().clear();490 mocks.clear();491 }492 @Override493 public TypeMockability isTypeMockable(final Class<?> type) {494 return new TypeMockability() {495 @Override496 public boolean mockable() {497 return INSTRUMENTATION.isModifiableClass(type) && !EXCLUDES.contains(type);498 }499 @Override500 public String nonMockableReason() {501 if (mockable()) {502 return "";503 }504 if (type.isPrimitive()) {505 return "primitive type";506 }507 if (EXCLUDES.contains(type)) {508 return "Cannot mock wrapper types, String.class or Class.class";509 }510 return "VM does not support modification of given type";511 }512 };513 }514 @Override515 public <T> StaticMockControl<T> createStaticMock(516 Class<T> type, MockCreationSettings<T> settings, MockHandler handler) {517 if (type == ConcurrentHashMap.class) {518 throw new MockitoException(519 "It is not possible to mock static methods of ConcurrentHashMap "520 + "to avoid infinitive loops within Mockito's implementation of static mock handling");521 } else if (type == Thread.class522 || type == System.class523 || type == Arrays.class524 || ClassLoader.class.isAssignableFrom(type)) {525 throw new MockitoException(526 "It is not possible to mock static methods of "527 + type.getName()528 + " to avoid interfering with class loading what leads to infinite loops");529 }530 bytecodeGenerator.mockClassStatic(type);531 Map<Class<?>, MockMethodInterceptor> interceptors = mockedStatics.get();532 if (interceptors == null) {533 interceptors = new WeakHashMap<>();534 mockedStatics.set(interceptors);535 }536 return new InlineStaticMockControl<>(type, interceptors, settings, handler);537 }538 @Override539 public <T> ConstructionMockControl<T> createConstructionMock(540 Class<T> type,541 Function<MockedConstruction.Context, MockCreationSettings<T>> settingsFactory,542 Function<MockedConstruction.Context, MockHandler<T>> handlerFactory,543 MockedConstruction.MockInitializer<T> mockInitializer) {544 if (type == Object.class) {545 throw new MockitoException(546 "It is not possible to mock construction of the Object class "547 + "to avoid inference with default object constructor chains");548 } else if (type.isPrimitive() || Modifier.isAbstract(type.getModifiers())) {549 throw new MockitoException(550 "It is not possible to construct primitive types or abstract types: "551 + type.getName());552 }553 bytecodeGenerator.mockClassConstruction(type);554 Map<Class<?>, BiConsumer<Object, MockedConstruction.Context>> interceptors =555 mockedConstruction.get();556 if (interceptors == null) {557 interceptors = new WeakHashMap<>();558 mockedConstruction.set(interceptors);559 }560 return new InlineConstructionMockControl<>(561 type, settingsFactory, handlerFactory, mockInitializer, interceptors);562 }563 @Override564 @SuppressWarnings("unchecked")565 public <T> T newInstance(Class<T> cls) throws InstantiationException {566 Constructor<?>[] constructors = cls.getDeclaredConstructors();567 if (constructors.length == 0) {568 throw new InstantiationException(cls.getName() + " does not define a constructor");569 }570 Constructor<?> selected = constructors[0];571 for (Constructor<?> constructor : constructors) {572 if (Modifier.isPublic(constructor.getModifiers())) {573 selected = constructor;574 break;575 }576 }577 Class<?>[] types = selected.getParameterTypes();578 Object[] arguments = new Object[types.length];579 int index = 0;580 for (Class<?> type : types) {581 arguments[index++] = makeStandardArgument(type);582 }583 MemberAccessor accessor = Plugins.getMemberAccessor();584 try {585 return (T)586 accessor.newInstance(587 selected,588 callback -> {589 mockitoConstruction.set(true);590 try {591 return callback.newInstance();592 } finally {593 mockitoConstruction.set(false);594 }595 },596 arguments);597 } catch (Exception e) {598 throw new InstantiationException("Could not instantiate " + cls.getName(), e);599 }600 }601 private Object makeStandardArgument(Class<?> type) {602 if (type == boolean.class) {603 return false;604 } else if (type == byte.class) {605 return (byte) 0;606 } else if (type == short.class) {607 return (short) 0;608 } else if (type == char.class) {609 return (char) 0;610 } else if (type == int.class) {611 return 0;612 } else if (type == long.class) {613 return 0L;614 } else if (type == float.class) {615 return 0f;616 } else if (type == double.class) {617 return 0d;618 } else {619 return null;620 }621 }622 private static class InlineStaticMockControl<T> implements StaticMockControl<T> {623 private final Class<T> type;624 private final Map<Class<?>, MockMethodInterceptor> interceptors;625 private final MockCreationSettings<T> settings;626 private final MockHandler handler;627 private InlineStaticMockControl(628 Class<T> type,629 Map<Class<?>, MockMethodInterceptor> interceptors,630 MockCreationSettings<T> settings,631 MockHandler handler) {632 this.type = type;633 this.interceptors = interceptors;634 this.settings = settings;635 this.handler = handler;636 }637 @Override638 public Class<T> getType() {639 return type;640 }641 @Override642 public void enable() {643 if (interceptors.putIfAbsent(type, new MockMethodInterceptor(handler, settings))644 != null) {645 throw new MockitoException(646 join(647 "For "648 + type.getName()649 + ", static mocking is already registered in the current thread",650 "",651 "To create a new mock, the existing static mock registration must be deregistered"));652 }653 }654 @Override655 public void disable() {656 if (interceptors.remove(type) == null) {657 throw new MockitoException(658 join(659 "Could not deregister "660 + type.getName()661 + " as a static mock since it is not currently registered",662 "",663 "To register a static mock, use Mockito.mockStatic("664 + type.getSimpleName()665 + ".class)"));666 }667 }668 }669 private class InlineConstructionMockControl<T> implements ConstructionMockControl<T> {670 private final Class<T> type;671 private final Function<MockedConstruction.Context, MockCreationSettings<T>> settingsFactory;672 private final Function<MockedConstruction.Context, MockHandler<T>> handlerFactory;673 private final MockedConstruction.MockInitializer<T> mockInitializer;674 private final Map<Class<?>, BiConsumer<Object, MockedConstruction.Context>> interceptors;675 private final List<Object> all = new ArrayList<>();676 private int count;677 private InlineConstructionMockControl(678 Class<T> type,679 Function<MockedConstruction.Context, MockCreationSettings<T>> settingsFactory,680 Function<MockedConstruction.Context, MockHandler<T>> handlerFactory,681 MockedConstruction.MockInitializer<T> mockInitializer,682 Map<Class<?>, BiConsumer<Object, MockedConstruction.Context>> interceptors) {683 this.type = type;684 this.settingsFactory = settingsFactory;685 this.handlerFactory = handlerFactory;686 this.mockInitializer = mockInitializer;687 this.interceptors = interceptors;688 }689 @Override690 public Class<T> getType() {691 return type;692 }693 @Override694 public void enable() {695 if (interceptors.putIfAbsent(696 type,697 (object, context) -> {698 ((InlineConstructionMockContext) context).count = ++count;699 MockMethodInterceptor interceptor =700 new MockMethodInterceptor(701 handlerFactory.apply(context),702 settingsFactory.apply(context));703 mocks.put(object, interceptor);704 try {705 @SuppressWarnings("unchecked")706 T cast = (T) object;707 mockInitializer.prepare(cast, context);708 } catch (Throwable t) {709 mocks.remove(object); // TODO: filter stack trace?710 throw new MockitoException(711 "Could not initialize mocked construction", t);712 }713 all.add(object);714 })715 != null) {716 throw new MockitoException(717 join(718 "For "719 + type.getName()720 + ", static mocking is already registered in the current thread",721 "",722 "To create a new mock, the existing static mock registration must be deregistered"));723 }724 }725 @Override726 public void disable() {727 if (interceptors.remove(type) == null) {728 throw new MockitoException(729 join(730 "Could not deregister "731 + type.getName()732 + " as a static mock since it is not currently registered",733 "",734 "To register a static mock, use Mockito.mockStatic("735 + type.getSimpleName()736 + ".class)"));737 }738 all.clear();739 }740 @Override741 @SuppressWarnings("unchecked")742 public List<T> getMocks() {743 return (List<T>) all;744 }745 }746 private static class InlineConstructionMockContext implements MockedConstruction.Context {747 private static final Map<String, Class<?>> PRIMITIVES = new HashMap<>();748 static {749 PRIMITIVES.put(boolean.class.getName(), boolean.class);750 PRIMITIVES.put(byte.class.getName(), byte.class);751 PRIMITIVES.put(short.class.getName(), short.class);752 PRIMITIVES.put(char.class.getName(), char.class);753 PRIMITIVES.put(int.class.getName(), int.class);754 PRIMITIVES.put(long.class.getName(), long.class);755 PRIMITIVES.put(float.class.getName(), float.class);756 PRIMITIVES.put(double.class.getName(), double.class);757 }758 private int count;759 private final Object[] arguments;760 private final Class<?> type;761 private final String[] parameterTypeNames;762 private InlineConstructionMockContext(763 Object[] arguments, Class<?> type, String[] parameterTypeNames) {764 this.arguments = arguments;765 this.type = type;766 this.parameterTypeNames = parameterTypeNames;767 }768 @Override769 public int getCount() {770 if (count == 0) {771 throw new MockitoConfigurationException(772 "mocked construction context is not initialized");773 }774 return count;775 }776 @Override...

Full Screen

Full Screen

InlineConstructionMockContext

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.creation.bytebuddy.InlineDelegateByteBuddyMockMaker2InlineDelegateByteBuddyMockMaker.inlineConstructionMockContext()3import org.mockito.internal.creation.bytebuddy.InlineDelegateByteBuddyMockMaker4InlineDelegateByteBuddyMockMaker.inlineDelegateByteBuddyMockMaker()5import org.mockito.internal.creation.bytebuddy.InlineDelegateByteBuddyMockMaker6InlineDelegateByteBuddyMockMaker.inlineMockContext()7import org.mockito.internal.creation.bytebuddy.InlineDelegateByteBuddyMockMaker8InlineDelegateByteBuddyMockMaker.inlineMockMaker()9import org.mockito.internal.creation.bytebuddy.InlineDelegateByteBuddyMockMaker10InlineDelegateByteBuddyMockMaker.inlineMockMaker$default()11import org.mockito.internal.creation.bytebuddy.InlineDelegateByteBuddyMockMak

Full Screen

Full Screen

InlineConstructionMockContext

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.creation.bytebuddy.InlineDelegateByteBuddyMockMaker;2import org.mockito.internal.creation.bytebuddy.InlineConstructionMockContext;3public class InlineConstructionMockContext {4 public static void main(String[] args) {5 InlineDelegateByteBuddyMockMaker mockMaker = new InlineDelegateByteBuddyMockMaker();6 InlineConstructionMockContext inlineConstructionMockContext = mockMaker.inlineConstructionMockContext();7 System.out.println(inlineConstructionMockContext);8 }9}

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