Search in sources :

Example 31 with MockClassLoader

use of org.powermock.core.classloader.MockClassLoader in project powermock by powermock.

the class ObjenesisClassloaderExecutorTest method worksWithObjectHierarchy.

@Test
public void worksWithObjectHierarchy() throws Exception {
    final MockClassLoader classloader = createClassloader();
    final MyHierarchicalFieldHolder tested = new MyHierarchicalFieldHolder();
    assertSame(tested.getMyArgument1(), tested.getMyArgument2());
    assertEquals(tested.getMyArgument3(), tested.getMyArgument2());
    new SingleClassloaderExecutor(classloader).execute(new Runnable() {

        public void run() {
            assertEquals(MockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName());
            assertSame(tested.getMyArgument1(), tested.getMyArgument2());
            assertEquals(tested.getMyArgument3(), tested.getMyArgument2());
        }
    });
}
Also used : MyHierarchicalFieldHolder(powermock.classloading.classes.MyHierarchicalFieldHolder) MockClassLoader(org.powermock.core.classloader.MockClassLoader) SingleClassloaderExecutor(org.powermock.classloading.SingleClassloaderExecutor) Test(org.junit.Test)

Example 32 with MockClassLoader

use of org.powermock.core.classloader.MockClassLoader in project powermock by powermock.

the class ObjenesisClassloaderExecutorTest method usesReferenceCloningWhenTwoFieldsPointToSameInstance.

@Test
public void usesReferenceCloningWhenTwoFieldsPointToSameInstance() throws Exception {
    final MockClassLoader classloader = createClassloader();
    final MyReferenceFieldHolder tested = new MyReferenceFieldHolder();
    assertSame(tested.getMyArgument1(), tested.getMyArgument2());
    assertSame(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT);
    new SingleClassloaderExecutor(classloader).execute(new Runnable() {

        public void run() {
            assertEquals(MockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName());
            assertEquals(tested.getMyArgument1(), tested.getMyArgument2());
            assertEquals(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT);
            assertSame(tested.getMyArgument1(), tested.getMyArgument2());
        // FIXME: This assertion should work:
        // assertSame(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT);
        }
    });
}
Also used : MockClassLoader(org.powermock.core.classloader.MockClassLoader) MyReferenceFieldHolder(powermock.classloading.classes.MyReferenceFieldHolder) SingleClassloaderExecutor(org.powermock.classloading.SingleClassloaderExecutor) Test(org.junit.Test)

Example 33 with MockClassLoader

use of org.powermock.core.classloader.MockClassLoader in project powermock by powermock.

the class PowerMock method doMock.

@SuppressWarnings("unchecked")
private static <T> T doMock(Class<T> type, boolean isStatic, MockStrategy mockStrategy, ConstructorArgs constructorArgs, Method... methods) {
    if (type == null) {
        throw new IllegalArgumentException("The class to mock cannot be null");
    }
    /*
         * Clear the EasyMock state after the test method is executed.
         */
    MockRepository.addAfterMethodRunner(new Runnable() {

        @Override
        public void run() {
            LastControl.reportLastControl(null);
        }
    });
    IMocksControl control = mockStrategy.createMockControl(type);
    MockRepository.addAfterMethodRunner(new EasyMockStateCleaner());
    T mock;
    if (type.isInterface()) {
        mock = control.createMock(type);
    } else if (type.getName().startsWith("java.") && Modifier.isFinal(type.getModifiers())) {
        Class<?> replicaType = createReplicaType(type, isStatic, constructorArgs);
        final Object replica = doCreateMock(replicaType, constructorArgs, control, methods);
        control = mockStrategy.createMockControl(replicaType);
        MockInvocationHandler h = new MockInvocationHandler((MocksControl) control);
        final Set<Method> methodsToMock = toSet(methods);
        if (isStatic) {
            MockRepository.putStaticMethodInvocationControl(type, new EasyMockMethodInvocationControl<Object>(h, methodsToMock, replica));
            MockRepository.addObjectsToAutomaticallyReplayAndVerify(type);
            return null;
        } else {
            final T newInstance;
            if (constructorArgs == null) {
                newInstance = Whitebox.newInstance(type);
                DefaultFieldValueGenerator.fillWithDefaultValues(newInstance);
            } else {
                try {
                    newInstance = (T) constructorArgs.getConstructor().newInstance(constructorArgs.getInitArgs());
                } catch (Exception e) {
                    throw new RuntimeException("Internal error", e);
                }
            }
            MockRepository.putInstanceMethodInvocationControl(newInstance, new EasyMockMethodInvocationControl<Object>(h, methodsToMock, replica));
            if (!(newInstance instanceof InvocationSubstitute<?>)) {
                MockRepository.addObjectsToAutomaticallyReplayAndVerify(newInstance);
            }
            return newInstance;
        }
    } else {
        mock = doCreateMock(type, constructorArgs, control, methods);
    }
    MockInvocationHandler h = new MockInvocationHandler((MocksControl) control);
    final Set<Method> methodsToMock = toSet(methods);
    if (isStatic) {
        MockRepository.putStaticMethodInvocationControl(type, new EasyMockMethodInvocationControl<T>(h, methodsToMock, mock));
        MockRepository.addObjectsToAutomaticallyReplayAndVerify(type);
    } else {
        MockRepository.putInstanceMethodInvocationControl(mock, new EasyMockMethodInvocationControl<T>(h, methodsToMock));
        if (!(mock instanceof InvocationSubstitute<?>)) {
            MockRepository.addObjectsToAutomaticallyReplayAndVerify(mock);
        }
    }
    ClassLoader classLoader = mock.getClass().getClassLoader();
    if (classLoader instanceof MockClassLoader) {
        ((MockClassLoader) classLoader).cache(mock.getClass());
    }
    return mock;
}
Also used : IMocksControl(org.easymock.IMocksControl) MocksControl(org.easymock.internal.MocksControl) MockClassLoader(org.powermock.core.classloader.MockClassLoader) EasyMockMethodInvocationControl(org.powermock.api.easymock.internal.invocationcontrol.EasyMockMethodInvocationControl) IMocksControl(org.easymock.IMocksControl) MockInvocationHandler(org.easymock.internal.MockInvocationHandler) InvocationSubstitute(org.powermock.core.spi.support.InvocationSubstitute) MockClassLoader(org.powermock.core.classloader.MockClassLoader)

Example 34 with MockClassLoader

use of org.powermock.core.classloader.MockClassLoader in project powermock by powermock.

the class DefaultMockCreator method createMethodInvocationControl.

@SuppressWarnings("unchecked")
private static <T> MockData<T> createMethodInvocationControl(final String mockName, Class<T> type, Method[] methods, boolean isSpy, Object delegator, MockSettings mockSettings) {
    final MockSettingsImpl settings;
    if (mockSettings == null) {
        // We change the context classloader to the current CL in order for the Mockito
        // framework to load it's plugins (such as MockMaker) correctly.
        final ClassLoader originalCL = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(DefaultMockCreator.class.getClassLoader());
        try {
            settings = (MockSettingsImpl) Mockito.withSettings();
            Plugins.getMockMaker();
        } finally {
            Thread.currentThread().setContextClassLoader(originalCL);
        }
    } else {
        settings = (MockSettingsImpl) mockSettings;
    }
    if (isSpy) {
        settings.defaultAnswer(Mockito.CALLS_REAL_METHODS);
    }
    settings.setMockName(new MockNameImpl(mockName));
    settings.setTypeToMock(type);
    InternalMockHandler mockHandler = MockHandlerFactory.createMockHandler(settings);
    MethodInterceptorFilter filter = new PowerMockMethodInterceptorFilter(mockHandler, settings);
    final T mock = new ClassImposterizer(new DefaultInstantiatorProvider().getInstantiator(settings)).imposterise(filter, type);
    ClassLoader classLoader = mock.getClass().getClassLoader();
    if (classLoader instanceof MockClassLoader) {
        MockClassLoader mcl = (MockClassLoader) classLoader;
        mcl.cache(mock.getClass());
    }
    final MockitoMethodInvocationControl invocationControl = new MockitoMethodInvocationControl(filter, isSpy && delegator == null ? new Object() : delegator, mock, methods);
    return new MockData<T>(invocationControl, mock);
}
Also used : MockSettingsImpl(org.mockito.internal.creation.MockSettingsImpl) MockClassLoader(org.powermock.core.classloader.MockClassLoader) ClassImposterizer(org.powermock.api.mockito.repackaged.ClassImposterizer) MockitoMethodInvocationControl(org.powermock.api.mockito.internal.invocation.MockitoMethodInvocationControl) MockNameImpl(org.mockito.internal.util.MockNameImpl) DefaultInstantiatorProvider(org.mockito.internal.creation.instance.DefaultInstantiatorProvider) MockClassLoader(org.powermock.core.classloader.MockClassLoader) InternalMockHandler(org.mockito.internal.InternalMockHandler) MethodInterceptorFilter(org.powermock.api.mockito.repackaged.MethodInterceptorFilter)

Example 35 with MockClassLoader

use of org.powermock.core.classloader.MockClassLoader in project powermock by powermock.

the class PowerMockMaker method createMock.

@Override
public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
    T mock = cglibMockMaker.createMock(settings, handler);
    ClassLoader classLoader = cglibMockMaker.getClass().getClassLoader();
    if (classLoader instanceof MockClassLoader) {
        MockClassLoader mcl = (MockClassLoader) classLoader;
        // The generated class is not picked up by PowerMock so we cache it here
        mcl.cache(mock.getClass());
    }
    return mock;
}
Also used : MockClassLoader(org.powermock.core.classloader.MockClassLoader) MockClassLoader(org.powermock.core.classloader.MockClassLoader)

Aggregations

MockClassLoader (org.powermock.core.classloader.MockClassLoader)35 Test (org.junit.Test)26 SingleClassloaderExecutor (org.powermock.classloading.SingleClassloaderExecutor)25 MyArgument (powermock.classloading.classes.MyArgument)8 MyReturnValue (powermock.classloading.classes.MyReturnValue)8 LinkedList (java.util.LinkedList)5 MockTransformer (org.powermock.core.transformers.MockTransformer)4 MyClass (powermock.classloading.classes.MyClass)4 Method (java.lang.reflect.Method)3 Collection (java.util.Collection)2 CtClass (javassist.CtClass)2 Ignore (org.junit.Ignore)2 IndicateReloadClass (org.powermock.core.IndicateReloadClass)2 ClassMockTransformer (org.powermock.core.transformers.impl.ClassMockTransformer)2 InterfaceMockTransformer (org.powermock.core.transformers.impl.InterfaceMockTransformer)2 MyCollectionHolder (powermock.classloading.classes.MyCollectionHolder)2 MyEnum (powermock.classloading.classes.MyEnum)2 MyEnumHolder (powermock.classloading.classes.MyEnumHolder)2 MyHierarchicalFieldHolder (powermock.classloading.classes.MyHierarchicalFieldHolder)2 MyHierarchicalOverloadedFieldHolder (powermock.classloading.classes.MyHierarchicalOverloadedFieldHolder)2