Revisited the way Guice creates an injector during unit test

The motivation of this is to enable test code to inject components from Jenkins, which means we need a single Injector that can see all of those, including @TestExtension and regular @Extension. Then I realized that the current implementation is broken, as it creates two independent Injectors. This has other undesirable side effects like @TestExtension components not being able to inject @Extensions, etc.

I briefly experimented with hierarchical Injectors (where we first create Injector that loads @Extension then create another that loads @TestExtension as a child), but this was hard to get right as we have no control over which ExtensionFinder gets instantiated first --- we'd be at the mercy of SezPoz.

So the eventual approach is to allow a single GuiceFinder to recognize multiple annotations. This also works well with our using child injector for installing plugins without restart
This commit is contained in:
Kohsuke Kawaguchi committed 2012-02-09 12:18:05 -08:00
1 parent 1472ce133b
commit a71d037b84
3 files changed
+95 -44

No files matched your search

@@ -25,6 +25,7 @@
package org.jvnet.hudson.test;
import com.gargoylesoftware.htmlunit.html.HtmlImage;
import com.google.inject.Injector;
import hudson.ClassicPluginStrategy;
import hudson.CloseProofOutputStream;
import hudson.DNSMultiCast;
@@ -324,6 +325,9 @@ public abstract class HudsonTestCase extends TestCase implements RootAction {
if (desc != null) Mailer.descriptor().setHudsonUrl(null);
for( Descriptor d : hudson.getExtensionList(Descriptor.class) )
d.load();
// allow the test class to inject Jenkins components
jenkins.lookup(Injector.class).injectMembers(this);
}
@@ -24,7 +24,7 @@
package org.jvnet.hudson.test;
import hudson.Extension;
import hudson.ExtensionFinder.AbstractGuiceFinder;
import hudson.ExtensionFinder.GuiceExtensionAnnotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
@@ -36,7 +36,7 @@ import java.lang.reflect.Method;
* @author Kohsuke Kawaguchi
*/
@Extension
public class TestExtensionLoader extends AbstractGuiceFinder<TestExtension> {
public class TestExtensionLoader extends GuiceExtensionAnnotation<TestExtension> {
public TestExtensionLoader() {
super(TestExtension.class);
}