mockit.internal.mockups.MockedImplementationClass Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jmockit Show documentation
Show all versions of jmockit Show documentation
JMockit is a Java toolkit for automated developer testing.
It contains APIs for the creation of the objects to be tested, for mocking dependencies, and for faking external
APIs; JUnit (4 & 5) and TestNG test runners are supported.
It also contains an advanced code coverage tool.
/*
* Copyright (c) 2006 Rogério Liesenfeld
* This file is subject to the terms of the MIT license (see LICENSE.txt).
*/
package mockit.internal.mockups;
import java.lang.reflect.*;
import java.lang.reflect.Type;
import javax.annotation.*;
import static java.lang.reflect.Modifier.*;
import mockit.*;
import mockit.external.asm.*;
import mockit.internal.classGeneration.*;
import mockit.internal.util.*;
public final class MockedImplementationClass
{
@Nonnull private final MockUp> mockUpInstance;
@Nullable private ImplementationClass implementationClass;
private Class generatedClass;
public MockedImplementationClass(@Nonnull MockUp> mockUpInstance) { this.mockUpInstance = mockUpInstance; }
@Nonnull
public Class createImplementation(@Nonnull Class interfaceToBeMocked, @Nullable Type typeToMock)
{
createImplementation(interfaceToBeMocked);
byte[] generatedBytecode = implementationClass == null ? null : implementationClass.getGeneratedBytecode();
MockClassSetup mockClassSetup = new MockClassSetup(generatedClass, typeToMock, mockUpInstance, generatedBytecode);
mockClassSetup.redefineMethodsInGeneratedClass();
return generatedClass;
}
@Nonnull
Class createImplementation(@Nonnull Class interfaceToBeMocked)
{
if (isPublic(interfaceToBeMocked.getModifiers())) {
generateImplementationForPublicInterface(interfaceToBeMocked);
}
else {
//noinspection unchecked
generatedClass = (Class) Proxy.getProxyClass(interfaceToBeMocked.getClassLoader(), interfaceToBeMocked);
}
return generatedClass;
}
private void generateImplementationForPublicInterface(@Nonnull Class interfaceToBeMocked)
{
implementationClass = new ImplementationClass(interfaceToBeMocked) {
@Nonnull @Override
protected ClassVisitor createMethodBodyGenerator(@Nonnull ClassReader typeReader)
{
return new InterfaceImplementationGenerator(typeReader, generatedClassName);
}
};
generatedClass = implementationClass.generateClass();
}
@Nonnull
public Class createImplementation(@Nonnull Type[] interfacesToBeMocked)
{
Class>[] interfacesToMock = new Class>[interfacesToBeMocked.length];
for (int i = 0; i < interfacesToMock.length; i++) {
interfacesToMock[i] = Utilities.getClassType(interfacesToBeMocked[i]);
}
//noinspection unchecked
generatedClass = (Class) Proxy.getProxyClass(ClassLoader.getSystemClassLoader(), interfacesToMock);
new MockClassSetup(generatedClass, null, mockUpInstance, null).redefineMethods();
return generatedClass;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy