Created
August 24, 2017 09:16
-
-
Save DarkholmeTenk/f430cf96de70b25b8fd01bc597b23abf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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