mockit.internal.injection.ConstructorInjection 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 mocking/faking APIs and a code coverage tool, supporting both JUnit and TestNG.
The mocking APIs allow all kinds of Java code, without testability restrictions, to be tested
in isolation from selected dependencies.
/*
* Copyright (c) 2006 Rogério Liesenfeld
* This file is subject to the terms of the MIT license (see LICENSE.txt).
*/
package mockit.internal.injection;
import java.lang.reflect.*;
import java.util.*;
import javax.annotation.*;
import mockit.internal.state.*;
import mockit.internal.util.*;
import static mockit.internal.injection.InjectionPoint.*;
import static mockit.internal.util.ConstructorReflection.*;
import static mockit.internal.util.Utilities.*;
final class ConstructorInjection extends Injector
{
@Nonnull private final Constructor> constructor;
ConstructorInjection(
@Nonnull TestedClass testedClass, @Nonnull InjectionState injectionState, @Nullable FullInjection fullInjection,
@Nonnull Constructor> constructor)
{
super(testedClass, injectionState, fullInjection);
this.constructor = constructor;
}
@Nonnull
Object instantiate(@Nonnull List parameterProviders)
{
Type[] parameterTypes = constructor.getGenericParameterTypes();
int n = parameterTypes.length;
Object[] arguments = n == 0 ? NO_ARGS : new Object[n];
boolean varArgs = constructor.isVarArgs();
if (varArgs) {
n--;
}
for (int i = 0; i < n; i++) {
Type parameterType = parameterTypes[i];
InjectionPointProvider parameterProvider = parameterProviders.get(i);
Object value;
if (parameterProvider instanceof ConstructorParameter) {
injectionState.setTypeOfInjectionPoint(parameterProvider.getDeclaredType());
String qualifiedName = getQualifiedName(parameterProvider.getAnnotations());
assert fullInjection != null;
value = fullInjection.createOrReuseInstance(this, parameterProvider, qualifiedName);
if (value == null) {
String parameterName = parameterProvider.getName();
throw new IllegalStateException(
"Missing @Tested or @Injectable" + missingValueDescription(parameterName));
}
}
else {
value = getArgumentValueToInject(parameterProvider);
}
arguments[i] = wrapInProviderIfNeeded(parameterType, value);
}
if (varArgs) {
Type parameterType = parameterTypes[n];
arguments[n] = obtainInjectedVarargsArray(parameterType);
}
TestRun.exitNoMockingZone();
try {
return invoke(constructor, arguments);
}
finally {
TestRun.enterNoMockingZone();
}
}
@Nonnull
private Object obtainInjectedVarargsArray(@Nonnull Type parameterType)
{
Type varargsElementType = getTypeOfInjectionPointFromVarargsParameter(parameterType);
injectionState.setTypeOfInjectionPoint(varargsElementType);
List