com.mycila.testing.plugin.guice.Guice2TestPlugin Maven / Gradle / Ivy
/**
* Copyright (C) 2008 Mathieu Carbou
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mycila.testing.plugin.guice;
import com.google.inject.AbstractModule;
import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.Stage;
import com.google.inject.TypeLiteral;
import com.google.inject.binder.AnnotatedBindingBuilder;
import com.google.inject.binder.LinkedBindingBuilder;
import com.google.inject.binder.ScopedBindingBuilder;
import com.google.inject.util.Modules;
import com.mycila.testing.core.AbstractTestPlugin;
import com.mycila.testing.core.Context;
import com.mycila.testing.core.TestPluginException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Mathieu Carbou ([email protected])
*/
public final class Guice2TestPlugin extends AbstractTestPlugin {
public void prepareTestInstance(final Context context) {
context.setAttribute("guice.providers", new ArrayList>());
GuiceContext ctx = context.getTest().getTargetClass().getAnnotation(GuiceContext.class);
// create modules
List modules = new ArrayList();
modules.add(new AbstractModule() {
@Override
protected void configure() {
bind(ProviderSetup.class).toInstance(new ProviderSetup() {
@Inject
void inject(Injector injector) {
for (Provider> provider : context.>>removeAttribute("guice.providers")) {
injector.injectMembers(provider);
}
}
});
}
});
modules.addAll(providedModules(context));
modules.add(bindings(context));
modules.add(providedBindings(context));
if (context.getTest().getTarget() instanceof Module) {
modules.add((Module) context.getTest().getTarget());
}
// create injector
Injector injector = Guice.createInjector(findStage(ctx), Modules.override(contextualModules(ctx)).with(modules));
context.setAttribute("com.google.inject.Injector", injector);
injector.injectMembers(context.getTest().getTarget());
}
private Module bindings(final Context context) {
return new Module() {
public void configure(Binder binder) {
for (final Field field : context.getTest().getFieldsAnnotatedWith(Bind.class)) {
Guice2TestPlugin.this.configure(context, binder, field.getGenericType(), field.getAnnotation(Bind.class), new InjectedProvider