Search in sources :

Example 1 with MemberAccessor

use of org.mockito.plugins.MemberAccessor in project mockito by mockito.

the class InlineDelegateByteBuddyMockMaker method newInstance.

@Override
@SuppressWarnings("unchecked")
public <T> T newInstance(Class<T> cls) throws InstantiationException {
    Constructor<?>[] constructors = cls.getDeclaredConstructors();
    if (constructors.length == 0) {
        throw new InstantiationException(cls.getName() + " does not define a constructor");
    }
    Constructor<?> selected = constructors[0];
    for (Constructor<?> constructor : constructors) {
        if (Modifier.isPublic(constructor.getModifiers())) {
            selected = constructor;
            break;
        }
    }
    Class<?>[] types = selected.getParameterTypes();
    Object[] arguments = new Object[types.length];
    int index = 0;
    for (Class<?> type : types) {
        arguments[index++] = makeStandardArgument(type);
    }
    MemberAccessor accessor = Plugins.getMemberAccessor();
    try {
        return (T) accessor.newInstance(selected, callback -> {
            mockitoConstruction.set(true);
            try {
                return callback.newInstance();
            } finally {
                mockitoConstruction.set(false);
            }
        }, arguments);
    } catch (Exception e) {
        throw new InstantiationException("Could not instantiate " + cls.getName(), e);
    }
}
Also used : SuppressSignatureCheck(org.mockito.internal.SuppressSignatureCheck) java.util(java.util) ByteBuddyAgent(net.bytebuddy.agent.ByteBuddyAgent) EXCLUDES(org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.EXCLUDES) MockCreationSettings(org.mockito.mock.MockCreationSettings) Platform(org.mockito.internal.util.Platform) JarFile(java.util.jar.JarFile) Constructor(java.lang.reflect.Constructor) Function(java.util.function.Function) MockitoException(org.mockito.exceptions.base.MockitoException) ConstructorInstantiator(org.mockito.internal.creation.instance.ConstructorInstantiator) JarEntry(java.util.jar.JarEntry) StringUtil.join(org.mockito.internal.util.StringUtil.join) MemberAccessor(org.mockito.plugins.MemberAccessor) BiConsumer(java.util.function.BiConsumer) WeakConcurrentMap(org.mockito.internal.util.concurrent.WeakConcurrentMap) MockHandler(org.mockito.invocation.MockHandler) JarOutputStream(java.util.jar.JarOutputStream) Instantiator(org.mockito.creation.instance.Instantiator) MockedConstruction(org.mockito.MockedConstruction) MockitoInitializationException(org.mockito.exceptions.base.MockitoInitializationException) Predicate(java.util.function.Predicate) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) Plugins(org.mockito.internal.configuration.plugins.Plugins) DetachedThreadLocal(org.mockito.internal.util.concurrent.DetachedThreadLocal) File(java.io.File) InlineMockMaker(org.mockito.plugins.InlineMockMaker) Instrumentation(java.lang.instrument.Instrumentation) InstantiationException(org.mockito.creation.instance.InstantiationException) Modifier(java.lang.reflect.Modifier) MockitoConfigurationException(org.mockito.exceptions.misusing.MockitoConfigurationException) InputStream(java.io.InputStream) Constructor(java.lang.reflect.Constructor) MockitoException(org.mockito.exceptions.base.MockitoException) MockitoInitializationException(org.mockito.exceptions.base.MockitoInitializationException) IOException(java.io.IOException) InstantiationException(org.mockito.creation.instance.InstantiationException) MockitoConfigurationException(org.mockito.exceptions.misusing.MockitoConfigurationException) MemberAccessor(org.mockito.plugins.MemberAccessor) InstantiationException(org.mockito.creation.instance.InstantiationException)

Example 2 with MemberAccessor

use of org.mockito.plugins.MemberAccessor in project mockito by mockito.

the class IndependentAnnotationEngine method process.

@Override
public AutoCloseable process(Class<?> clazz, Object testInstance) {
    List<ScopedMock> scopedMocks = new ArrayList<>();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        boolean alreadyAssigned = false;
        for (Annotation annotation : field.getAnnotations()) {
            Object mock = createMockFor(annotation, field);
            if (mock instanceof ScopedMock) {
                scopedMocks.add((ScopedMock) mock);
            }
            if (mock != null) {
                throwIfAlreadyAssigned(field, alreadyAssigned);
                alreadyAssigned = true;
                final MemberAccessor accessor = Plugins.getMemberAccessor();
                try {
                    accessor.set(field, testInstance, mock);
                } catch (Exception e) {
                    for (ScopedMock scopedMock : scopedMocks) {
                        scopedMock.close();
                    }
                    throw new MockitoException("Problems setting field " + field.getName() + " annotated with " + annotation, e);
                }
            }
        }
    }
    return () -> {
        for (ScopedMock scopedMock : scopedMocks) {
            scopedMock.closeOnDemand();
        }
    };
}
Also used : Field(java.lang.reflect.Field) MemberAccessor(org.mockito.plugins.MemberAccessor) MockitoException(org.mockito.exceptions.base.MockitoException) ScopedMock(org.mockito.ScopedMock) ArrayList(java.util.ArrayList) Annotation(java.lang.annotation.Annotation) MockitoException(org.mockito.exceptions.base.MockitoException)

Example 3 with MemberAccessor

use of org.mockito.plugins.MemberAccessor in project mockito by mockito.

the class SpyAnnotationEngine method spyNewInstance.

private static Object spyNewInstance(Object testInstance, Field field) throws InstantiationException, IllegalAccessException, InvocationTargetException {
    MockSettings settings = withSettings().defaultAnswer(CALLS_REAL_METHODS).name(field.getName());
    Class<?> type = field.getType();
    if (type.isInterface()) {
        return Mockito.mock(type, settings.useConstructor());
    }
    int modifiers = type.getModifiers();
    if (typeIsPrivateAbstractInnerClass(type, modifiers)) {
        throw new MockitoException(join("@Spy annotation can't initialize private abstract inner classes.", "  inner class: '" + type.getSimpleName() + "'", "  outer class: '" + type.getEnclosingClass().getSimpleName() + "'", "", "You should augment the visibility of this inner class"));
    }
    if (typeIsNonStaticInnerClass(type, modifiers)) {
        Class<?> enclosing = type.getEnclosingClass();
        if (!enclosing.isInstance(testInstance)) {
            throw new MockitoException(join("@Spy annotation can only initialize inner classes declared in the test.", "  inner class: '" + type.getSimpleName() + "'", "  outer class: '" + enclosing.getSimpleName() + "'", ""));
        }
        return Mockito.mock(type, settings.useConstructor().outerInstance(testInstance));
    }
    Constructor<?> constructor = noArgConstructorOf(type);
    if (Modifier.isPrivate(constructor.getModifiers())) {
        MemberAccessor accessor = Plugins.getMemberAccessor();
        return Mockito.mock(type, settings.spiedInstance(accessor.newInstance(constructor)));
    } else {
        return Mockito.mock(type, settings.useConstructor());
    }
}
Also used : MemberAccessor(org.mockito.plugins.MemberAccessor) MockitoException(org.mockito.exceptions.base.MockitoException) MockSettings(org.mockito.MockSettings)

Example 4 with MemberAccessor

use of org.mockito.plugins.MemberAccessor in project mockito by mockito.

the class TerminalMockCandidateFilter method filterCandidate.

@Override
public OngoingInjector filterCandidate(final Collection<Object> mocks, final Field candidateFieldToBeInjected, final List<Field> allRemainingCandidateFields, final Object injectee) {
    if (mocks.size() == 1) {
        final Object matchingMock = mocks.iterator().next();
        MemberAccessor accessor = Plugins.getMemberAccessor();
        return () -> {
            try {
                if (!new BeanPropertySetter(injectee, candidateFieldToBeInjected).set(matchingMock)) {
                    accessor.set(candidateFieldToBeInjected, injectee, matchingMock);
                }
            } catch (RuntimeException | IllegalAccessException e) {
                throw cannotInjectDependency(candidateFieldToBeInjected, matchingMock, e);
            }
            return matchingMock;
        };
    }
    return OngoingInjector.nop;
}
Also used : MemberAccessor(org.mockito.plugins.MemberAccessor) BeanPropertySetter(org.mockito.internal.util.reflection.BeanPropertySetter)

Example 5 with MemberAccessor

use of org.mockito.plugins.MemberAccessor in project mockito by mockito.

the class BeanPropertySetter method set.

/**
 * Set the value to the property represented by this {@link BeanPropertySetter}
 * @param value the new value to pass to the property setter
 * @return <code>true</code> if the value has been injected, <code>false</code> otherwise
 * @throws RuntimeException Can be thrown if the setter threw an exception, if the setter is not accessible
 *          or, if <code>reportNoSetterFound</code> and setter could not be found.
 */
public boolean set(final Object value) {
    MemberAccessor accessor = Plugins.getMemberAccessor();
    Method writeMethod = null;
    try {
        writeMethod = target.getClass().getMethod(setterName(field.getName()), field.getType());
        accessor.invoke(writeMethod, target, value);
        return true;
    } catch (InvocationTargetException e) {
        throw new RuntimeException("Setter '" + writeMethod + "' of '" + target + "' with value '" + value + "' threw exception : '" + e.getTargetException() + "'", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Access not authorized on field '" + field + "' of object '" + target + "' with value: '" + value + "'", e);
    } catch (NoSuchMethodException e) {
        reportNoSetterFound();
    }
    reportNoSetterFound();
    return false;
}
Also used : MemberAccessor(org.mockito.plugins.MemberAccessor) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

MemberAccessor (org.mockito.plugins.MemberAccessor)9 MockitoException (org.mockito.exceptions.base.MockitoException)4 Field (java.lang.reflect.Field)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 Method (java.lang.reflect.Method)2 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 Annotation (java.lang.annotation.Annotation)1 Instrumentation (java.lang.instrument.Instrumentation)1 Constructor (java.lang.reflect.Constructor)1 Modifier (java.lang.reflect.Modifier)1 java.util (java.util)1 ArrayList (java.util.ArrayList)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 BiConsumer (java.util.function.BiConsumer)1 Function (java.util.function.Function)1 Predicate (java.util.function.Predicate)1 JarEntry (java.util.jar.JarEntry)1