Skip to content

Instantly share code, notes, and snippets.

@DarkholmeTenk
Created August 24, 2017 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DarkholmeTenk/f430cf96de70b25b8fd01bc597b23abf to your computer and use it in GitHub Desktop.
Save DarkholmeTenk/f430cf96de70b25b8fd01bc597b23abf to your computer and use it in GitHub Desktop.
import static org.junit.Assert.assertFalse;
import org.junit.Before;
import org.junit.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.matcher.Matchers;
import com.google.inject.spi.ProvisionListener;
public class GuiceBrokenExample
{
private boolean failed = true;
@Before
public void resetFailure()
{
failed = true;
}
//When constructed in to the same injector, the test passes because the ListeningModule gets a
// chance to notice the Injectable being provisioned
@Test
public void test()
{
Injector i = Guice.createInjector(new ListeningModule());
i.getInstance(Injectable.class);
assertFalse(failed);
}
//This test fails because the original injector actually constructs the Injectable instance
// because it doesn't require anything from the listening module
@Test
public void testFails()
{
Injector i = Guice.createInjector();
i = i.createChildInjector(new ListeningModule());
i.getInstance(Injectable.class);
assertFalse(failed);
}
private class ListeningModule extends AbstractModule
{
@Override
protected void configure()
{
this.bindListener(Matchers.any(), new ProvListen());
}
}
private class ProvListen implements ProvisionListener
{
@Override
public <T> void onProvision(ProvisionInvocation<T> provision)
{
failed = false;
}
}
public static class Injectable
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment