com.google.inject.Injector

Here are the examples of the java api class com.google.inject.Injector taken from open source projects.

1. AssignmentsModuleTest#testConfigure()

Project: wasabi
File: AssignmentsModuleTest.java
@Ignore
public void testConfigure() throws Exception {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(MutexRepository.class).toInstance(mock(CassandraMutexRepository.class));
        }
    }, new AssignmentsModule());
    injector.getInstance(Key.get(boolean.class, Names.named("decision.engine.use.proxy")));
    injector.getInstance(Key.get(int.class, Names.named("decision.engine.connection.timeout")));
    injector.getInstance(Key.get(int.class, Names.named("decision.engine.read.timeout")));
    injector.getInstance(Key.get(boolean.class, Names.named("decision.engine.use.connection.pooling")));
    injector.getInstance(Key.get(int.class, Names.named("decision.engine.max.connections.per.host")));
    injector.getInstance(Key.get(int.class, Names.named("assignment.http.proxy.portt")));
    injector.getInstance(Key.get(String.class, Names.named("assignment.http.proxy.host")));
    //RuleCacheEngine
    injector.getInstance(Key.get(ThreadPoolExecutor.class, Names.named("ruleCache.threadPool")));
    assertThat(injector.getInstance(Key.get(Assignments.class)), is(not(nullValue())));
}

2. Jsr330Test#testBindProviderClass()

Project: guice
File: Jsr330Test.java
/**
   * This test verifies that we can compile bindings to provider instances
   * whose compile-time type implements javax.inject.Provider but not
   * com.google.inject.Provider. For binary compatibility, we don't (and won't)
   * support binding to instances of javax.inject.Provider.
   */
public void testBindProviderClass() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        protected void configure() {
            bind(B.class).toProvider(BProvider.class);
            bind(B.class).annotatedWith(Names.named("1")).toProvider(BProvider.class);
            bind(B.class).annotatedWith(Names.named("2")).toProvider(Key.get(BProvider.class));
            bind(B.class).annotatedWith(Names.named("3")).toProvider(TypeLiteral.get(BProvider.class));
        }
    });
    injector.getInstance(Key.get(B.class));
    injector.getInstance(Key.get(B.class, Names.named("1")));
    injector.getInstance(Key.get(B.class, Names.named("2")));
    injector.getInstance(Key.get(B.class, Names.named("3")));
}

3. UDPBasicTest#testSingleMessage()

Project: incubator-s4
File: UDPBasicTest.java
@Test
public void testSingleMessage() throws Exception {
    Injector injector1 = Guice.createInjector(Modules.override(new TestCommModule(Resources.getResource("default.s4.comm.properties").openStream())).with(new UDPTransportModule(), new NoOpReceiverModule()));
    // this picks partition 0
    Emitter emitter = injector1.getInstance(Emitter.class);
    Injector injector2 = Guice.createInjector(Modules.override(new TestCommModule(Resources.getResource("default.s4.comm.properties").openStream())).with(new UDPTransportModule(), new MockReceiverModule()));
    // creating the listener will inject assignment (i.e. assign a partition) and receiver (delegatee for
    // listener)
    injector2.getInstance(Listener.class);
    // send to the other partition (1)
    emitter.send(1, injector1.getInstance(SerializerDeserializer.class).serialize(CommTestUtils.MESSAGE));
    Assert.assertTrue(CommTestUtils.SIGNAL_MESSAGE_RECEIVED.await(5, TimeUnit.SECONDS));
}

4. TCPBasicTest#testSingleMessage()

Project: incubator-s4
File: TCPBasicTest.java
@Test
public void testSingleMessage() throws Exception {
    Injector injector1 = Guice.createInjector(Modules.override(new TestCommModule(Resources.getResource("default.s4.comm.properties").openStream())).with(new TCPTransportModule(), new NoOpReceiverModule()));
    // this node picks partition 0
    Emitter emitter = injector1.getInstance(Emitter.class);
    Injector injector2 = Guice.createInjector(Modules.override(new TestCommModule(Resources.getResource("default.s4.comm.properties").openStream())).with(new TCPTransportModule(), new MockReceiverModule()));
    // creating the listener will inject assignment (i.e. assign a partition) and receiver (delegatee for
    // listener, here a mock which simply intercepts the message and notifies through a countdown latch)
    injector2.getInstance(Listener.class);
    // send to the other node
    emitter.send(1, injector1.getInstance(SerializerDeserializer.class).serialize(CommTestUtils.MESSAGE));
    // check receiver got the message
    Assert.assertTrue(CommTestUtils.SIGNAL_MESSAGE_RECEIVED.await(5, TimeUnit.SECONDS));
}

5. ProviderMethodsTest#testInjectsJustOneLogger()

Project: guice
File: ProviderMethodsTest.java
public void testInjectsJustOneLogger() {
    AtomicReference<Logger> loggerRef = new AtomicReference<Logger>();
    Injector injector = Guice.createInjector(new FooModule(loggerRef));
    assertNull(loggerRef.get());
    injector.getInstance(Integer.class);
    Logger lastLogger = loggerRef.getAndSet(null);
    assertNotNull(lastLogger);
    injector.getInstance(Integer.class);
    assertSame(lastLogger, loggerRef.get());
    assertEquals(FooModule.class.getName(), lastLogger.getName());
}

6. ModuleAnnotatedMethodScannerTest#testChildInjectorScannersDontImpactSiblings()

Project: guice
File: ModuleAnnotatedMethodScannerTest.java
public void testChildInjectorScannersDontImpactSiblings() {
    Module module = new AbstractModule() {

        @Override
        protected void configure() {
        }

        @TestProvides
        @Named("foo")
        String foo() {
            return "foo";
        }
    };
    Injector parent = Guice.createInjector();
    Injector child = parent.createChildInjector(NamedMunger.module(), module);
    assertMungedBinding(child, String.class, "foo", "foo");
    // no foo nor foo-munged in sibling, since scanner never saw it.
    Injector sibling = parent.createChildInjector(module);
    assertNull(sibling.getExistingBinding(Key.get(String.class, named("foo"))));
    assertNull(sibling.getExistingBinding(Key.get(String.class, named("foo-munged"))));
}

7. TestAutoBindSingletonScopes#scopesAreHonoredInProdNoChild()

Project: governator
File: TestAutoBindSingletonScopes.java
@Test
public void scopesAreHonoredInProdNoChild() {
    Injector injector = LifecycleInjector.builder().inStage(Stage.PRODUCTION).withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS).usingBasePackages("com.netflix.governator.autobind.scopes").build().createInjector();
    injector.getInstance(AutoBindEagerSingleton.class);
    injector.getInstance(AutoBindEagerSingleton.class);
    Assert.assertEquals(1, AutoBindEagerSingleton.counter.get());
    Assert.assertEquals(0, AutoBindNotEagerSingleton.counter.get());
    Assert.assertEquals(0, AutoBindLazySingleton.counter.get());
}

8. TestAutoBindSingletonScopes#scopesAreHonoredInDevModeNoChild()

Project: governator
File: TestAutoBindSingletonScopes.java
@Test
public void scopesAreHonoredInDevModeNoChild() {
    Injector injector = LifecycleInjector.builder().inStage(Stage.DEVELOPMENT).withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS).usingBasePackages("com.netflix.governator.autobind.scopes").build().createInjector();
    injector.getInstance(AutoBindEagerSingleton.class);
    injector.getInstance(AutoBindEagerSingleton.class);
    Assert.assertEquals(1, AutoBindEagerSingleton.counter.get());
    Assert.assertEquals(0, AutoBindNotEagerSingleton.counter.get());
    Assert.assertEquals(0, AutoBindLazySingleton.counter.get());
}

9. TestAutoBindSingletonScopes#scopesAreHonoredInProd()

Project: governator
File: TestAutoBindSingletonScopes.java
@Test
public void scopesAreHonoredInProd() {
    Injector injector = LifecycleInjector.builder().inStage(Stage.PRODUCTION).usingBasePackages("com.netflix.governator.autobind.scopes").build().createInjector();
    injector.getInstance(AutoBindEagerSingleton.class);
    injector.getInstance(AutoBindEagerSingleton.class);
    Assert.assertEquals(1, AutoBindEagerSingleton.counter.get());
    Assert.assertEquals(0, AutoBindNotEagerSingleton.counter.get());
    Assert.assertEquals(0, AutoBindLazySingleton.counter.get());
}

10. TestAutoBindSingletonScopes#scopesAreHonoredInDevMode()

Project: governator
File: TestAutoBindSingletonScopes.java
@Test
public void scopesAreHonoredInDevMode() {
    Injector injector = LifecycleInjector.builder().inStage(Stage.DEVELOPMENT).usingBasePackages("com.netflix.governator.autobind.scopes").build().createInjector();
    injector.getInstance(AutoBindEagerSingleton.class);
    injector.getInstance(AutoBindEagerSingleton.class);
    Assert.assertEquals(1, AutoBindEagerSingleton.counter.get());
    Assert.assertEquals(0, AutoBindNotEagerSingleton.counter.get());
    Assert.assertEquals(0, AutoBindLazySingleton.counter.get());
}

11. MapBinderTest#testMapBinderAggregationForAnnotationType()

Project: guice
File: MapBinderTest.java
public void testMapBinderAggregationForAnnotationType() {
    Module module = new AbstractModule() {

        @Override
        protected void configure() {
            MapBinder<String, String> multibinder = MapBinder.newMapBinder(binder(), String.class, String.class, Abc.class);
            multibinder.addBinding("a").toInstance("A");
            multibinder.addBinding("b").toInstance("B");
            multibinder = MapBinder.newMapBinder(binder(), String.class, String.class, Abc.class);
            multibinder.addBinding("c").toInstance("C");
        }
    };
    Injector injector = Guice.createInjector(module);
    Key<Map<String, String>> key = Key.get(mapOfString, Abc.class);
    Map<String, String> abc = injector.getInstance(key);
    assertEquals(mapOf("a", "A", "b", "B", "c", "C"), abc);
    assertMapVisitor(key, stringType, stringType, setOf(module), BOTH, false, 0, instance("a", "A"), instance("b", "B"), instance("c", "C"));
    // just make sure these succeed
    injector.getInstance(Key.get(mapOfStringProvider, Abc.class));
    injector.getInstance(Key.get(mapOfStringJavaxProvider, Abc.class));
}

12. MapBinderTest#testMapBinderAggregationForAnnotationInstance()

Project: guice
File: MapBinderTest.java
public void testMapBinderAggregationForAnnotationInstance() {
    Module module = new AbstractModule() {

        @Override
        protected void configure() {
            MapBinder<String, String> multibinder = MapBinder.newMapBinder(binder(), String.class, String.class, Names.named("abc"));
            multibinder.addBinding("a").toInstance("A");
            multibinder.addBinding("b").toInstance("B");
            multibinder = MapBinder.newMapBinder(binder(), String.class, String.class, Names.named("abc"));
            multibinder.addBinding("c").toInstance("C");
        }
    };
    Injector injector = Guice.createInjector(module);
    Key<Map<String, String>> key = Key.get(mapOfString, Names.named("abc"));
    Map<String, String> abc = injector.getInstance(key);
    assertEquals(mapOf("a", "A", "b", "B", "c", "C"), abc);
    assertMapVisitor(key, stringType, stringType, setOf(module), BOTH, false, 0, instance("a", "A"), instance("b", "B"), instance("c", "C"));
    // just make sure these succeed
    injector.getInstance(Key.get(mapOfStringProvider, Names.named("abc")));
    injector.getInstance(Key.get(mapOfStringJavaxProvider, Names.named("abc")));
}

13. TransactionServiceTest#createTxService()

Project: cdap
File: TransactionServiceTest.java
static TransactionService createTxService(String zkConnectionString, int txServicePort, Configuration hConf, final File outPath) {
    final CConfiguration cConf = CConfiguration.create();
    // tests should use the current user for HDFS
    cConf.set(Constants.CFG_HDFS_USER, System.getProperty("user.name"));
    cConf.set(Constants.Zookeeper.QUORUM, zkConnectionString);
    cConf.set(Constants.CFG_LOCAL_DATA_DIR, outPath.getAbsolutePath());
    cConf.set(TxConstants.Service.CFG_DATA_TX_BIND_PORT, Integer.toString(txServicePort));
    // we want persisting for this test
    cConf.setBoolean(TxConstants.Manager.CFG_DO_PERSIST, true);
    final Injector injector = Guice.createInjector(new ConfigModule(cConf, hConf), // Use local location factory
    new LocationRuntimeModule().getInMemoryModules(), new ZKClientModule(), new DiscoveryRuntimeModule().getDistributedModules(), new TransactionMetricsModule(), new DataFabricModules().getDistributedModules(), new SystemDatasetRuntimeModule().getInMemoryModules(), new DataSetsModules().getInMemoryModules());
    injector.getInstance(ZKClientService.class).startAndWait();
    return injector.getInstance(TransactionService.class);
}

14. HBaseKVTableTest#getDefinition()

Project: cdap
File: HBaseKVTableTest.java
@Override
protected DatasetDefinition<? extends NoTxKeyValueTable, ? extends DatasetAdmin> getDefinition() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(CConfiguration.class).toInstance(CConfiguration.create());
            bind(Configuration.class).toInstance(TEST_HBASE.getConfiguration());
            bind(HBaseTableUtil.class).toInstance(hBaseTableUtil);
        }
    });
    HBaseKVTableDefinition def = new HBaseKVTableDefinition("foo");
    injector.injectMembers(def);
    return def;
}

15. LevelDBKVTableTest#getDefinition()

Project: cdap
File: LevelDBKVTableTest.java
@Override
protected DatasetDefinition<? extends NoTxKeyValueTable, ? extends DatasetAdmin> getDefinition() throws IOException {
    final String dataDir = tmpFolder.newFolder().getAbsolutePath();
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            CConfiguration conf = CConfiguration.create();
            conf.set(Constants.CFG_DATA_LEVELDB_DIR, dataDir);
            bind(CConfiguration.class).toInstance(conf);
            bind(LevelDBTableService.class).toInstance(service);
        }
    });
    LevelDBKVTableDefinition def = new LevelDBKVTableDefinition("foo");
    injector.injectMembers(def);
    return def;
}

16. InjectorManager#beforeTest()

Project: camel
File: InjectorManager.java
public void beforeTest(Object test) throws Exception {
    Preconditions.checkNotNull(test, "test");
    Class<? extends Object> testType = test.getClass();
    moduleType = getModuleForTestClass(testType);
    Injector classInjector = injectors.get(moduleType);
    if (classInjector == null) {
        classInjector = createInjector(moduleType);
        Preconditions.checkNotNull(classInjector, "classInjector");
        injectors.put(moduleType, classInjector);
    }
    injectors.put(testType, classInjector);
    classInjector.injectMembers(test);
}

17. MigrationManagerImplIT#testRollback()

Project: aurora
File: MigrationManagerImplIT.java
@Test
public void testRollback() throws Exception {
    // Run a normal migration which will apply one the change found in the testmigration package.
    MigrationLoader loader = new JavaMigrationLoader("org.apache.aurora.scheduler.storage.db.testmigration");
    Injector injector = createMigrationInjector(loader);
    MigrationManager migrationManager = injector.getInstance(MigrationManager.class);
    migrationManager.migrate();
    // Now we intentionally pass a reference to a non-existent package to ensure that no migrations
    // are found. As such a rollback is expected to be detected and a downgrade be performed.
    MigrationLoader rollbackLoader = new JavaMigrationLoader("org.apache.aurora.scheduler.storage.db.nomigrations");
    Injector rollbackInjector = createMigrationInjector(rollbackLoader);
    MigrationManager rollbackManager = rollbackInjector.getInstance(MigrationManager.class);
    rollbackManager.migrate();
    assertRollbackComplete(rollbackInjector.getInstance(SqlSessionFactory.class));
}

18. PreemptorModuleTest#testPreemptorDisabled()

Project: aurora
File: PreemptorModuleTest.java
@Test
public void testPreemptorDisabled() throws Exception {
    Injector injector = createInjector(new PreemptorModule(false, Amount.of(0L, Time.SECONDS), Amount.of(0L, Time.SECONDS)));
    control.replay();
    injector.getBindings();
    assertEquals(Optional.absent(), injector.getInstance(Preemptor.class).attemptPreemptionFor(IAssignedTask.build(new AssignedTask()), AttributeAggregate.EMPTY, storageUtil.mutableStoreProvider));
}

19. AsyncModuleTest#testBindings()

Project: aurora
File: AsyncModuleTest.java
@Test
public void testBindings() throws Exception {
    Injector injector = createInjector(new AsyncModule());
    control.replay();
    Set<Service> services = injector.getInstance(Key.get(new TypeLiteral<Set<Service>>() {
    }, AppStartup.class));
    for (Service service : services) {
        service.startAsync().awaitRunning();
    }
    injector.getBindings();
    assertEquals(ImmutableMap.of(RegisterGauges.TIMEOUT_QUEUE_GAUGE, 0, RegisterGauges.ASYNC_TASKS_GAUGE, 0L, RegisterGauges.DELAY_QUEUE_GAUGE, 0), statsProvider.getAllValues());
}

20. InjectConfigTest#testBinding()

Project: apex-core
File: InjectConfigTest.java
@Test
public void testBinding() throws Exception {
    Configuration conf = new Configuration(false);
    conf.set("stringKey", "someStringValue");
    conf.set("urlKey", "http://localhost:9999");
    conf.set("stringArrayKey", "a,b,c");
    // ensure super classes are processed
    MyBean bean = new MyBeanExt();
    Injector injector = Guice.createInjector(new TestGuiceModule(conf));
    injector.injectMembers(bean);
    Assert.assertEquals("", "someStringValue", bean.stringField);
    Assert.assertEquals("", new java.net.URL(conf.get("urlKey")), bean.urlField);
    Assert.assertArrayEquals("", new String[] { "a", "b", "c" }, bean.stringArrayField);
}

21. TestLifeCycleManager#testNoPreDestroy()

Project: airlift
File: TestLifeCycleManager.java
@Test
public void testNoPreDestroy() throws Exception {
    Injector injector = Guice.createInjector(Stage.PRODUCTION, new LifeCycleModule(),  binder -> {
        binder.bind(PostConstructOnly.class).in(Scopes.SINGLETON);
        binder.bind(PreDestroyOnly.class).in(Scopes.SINGLETON);
    });
    injector.getInstance(PostConstructOnly.class);
    LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class);
    lifeCycleManager.start();
    Assert.assertEquals(stateLog, ImmutableList.of("makeMe"));
    lifeCycleManager.stop();
    Assert.assertEquals(stateLog, ImmutableList.of("makeMe", "unmakeMe"));
}

22. TestLifeCycleManager#testJITInjection()

Project: airlift
File: TestLifeCycleManager.java
@Test
public void testJITInjection() throws Exception {
    Injector injector = Guice.createInjector(Stage.PRODUCTION, new LifeCycleModule(),  binder -> {
        binder.bind(AnInstance.class).in(Scopes.SINGLETON);
        binder.bind(DependentInstance.class).in(Scopes.SINGLETON);
    });
    injector.getInstance(AnInstance.class);
    LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class);
    lifeCycleManager.start();
    lifeCycleManager.stop();
    Assert.assertEquals(stateLog, ImmutableList.of("postDependentInstance", "preDependentInstance"));
}

23. TestLifeCycleManager#testDeepDependency()

Project: airlift
File: TestLifeCycleManager.java
@Test
public void testDeepDependency() throws Exception {
    Injector injector = Guice.createInjector(Stage.PRODUCTION, new LifeCycleModule(),  binder -> {
        binder.bind(AnInstance.class).in(Scopes.SINGLETON);
        binder.bind(AnotherInstance.class).in(Scopes.SINGLETON);
        binder.bind(DependentInstance.class).in(Scopes.SINGLETON);
    });
    injector.getInstance(AnotherInstance.class);
    LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class);
    lifeCycleManager.start();
    Assert.assertEquals(stateLog, ImmutableList.of("postDependentInstance"));
    lifeCycleManager.stop();
    Assert.assertEquals(stateLog, ImmutableList.of("postDependentInstance", "preDependentInstance"));
}

24. TestRunner#getInjector()

Project: testng
File: TestRunner.java
@Override
public Injector getInjector(IClass iClass) {
    Annotation annotation = AnnotationHelper.findAnnotationSuperClasses(Guice.class, iClass.getRealClass());
    if (annotation == null)
        return null;
    if (iClass instanceof TestClass) {
        iClass = ((TestClass) iClass).getIClass();
    }
    if (!(iClass instanceof ClassImpl))
        return null;
    Injector parentInjector = ((ClassImpl) iClass).getParentInjector();
    Guice guice = (Guice) annotation;
    List<Module> moduleInstances = Lists.newArrayList(getModules(guice, parentInjector, iClass.getRealClass()));
    // Reuse the previous injector, if any
    Injector injector = getInjector(moduleInstances);
    if (injector == null) {
        injector = parentInjector.createChildInjector(moduleInstances);
        addInjector(moduleInstances, injector);
    }
    return injector;
}

25. TestHelper#overridenInjector()

Project: scdl
File: TestHelper.java
public static void overridenInjector(Object instance, AbstractModule module) {
    final Application app = Robolectric.application;
    // Allow overriding of integrated classes like Activity
    Module moduleOverride = Modules.override(RoboGuice.newDefaultRoboModule(app)).with(module);
    // Also allow overriding custom bindings like URLWrapper
    moduleOverride = Modules.override(new SCDLModule()).with(moduleOverride);
    RoboGuice.setBaseApplicationInjector(app, RoboGuice.DEFAULT_STAGE, moduleOverride);
    final Injector injector = TestHelper.getInjector();
    injector.injectMembers(instance);
}

26. UtilTestSuiteWithEmbeddedDB#beforeClass()

Project: killbill
File: UtilTestSuiteWithEmbeddedDB.java
@BeforeClass(groups = "slow")
public void beforeClass() throws Exception {
    final Injector g = Guice.createInjector(Stage.PRODUCTION, new TestUtilModuleWithEmbeddedDB(configSource));
    g.injectMembers(this);
    if (DBEngine.MYSQL.equals(helper.getDBEngine())) {
        Assert.assertTrue(locker instanceof MySqlGlobalLocker);
    } else if (DBEngine.POSTGRESQL.equals(helper.getDBEngine())) {
        Assert.assertTrue(locker instanceof PostgreSQLGlobalLocker);
    } else {
        Assert.assertTrue(locker instanceof MemoryGlobalLocker);
    }
    Assert.assertTrue(locker.isFree("a", "b"));
}

27. GuiceAnnotationBuilder#createInjector()

Project: jbehave-core
File: GuiceAnnotationBuilder.java
protected Injector createInjector(List<Module> modules) {
    if (injector != null) {
        return injector;
    }
    Injector root = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
        }
    });
    return root.createChildInjector(Modules.combine(modules));
}

28. OptionalBinderTest#testWeakKeySet_integration()

Project: guice
File: OptionalBinderTest.java
// Tests for com.google.inject.internal.WeakKeySet not leaking memory.
public void testWeakKeySet_integration() {
    Injector parentInjector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(String.class).toInstance("hi");
        }
    });
    WeakKeySetUtils.assertNotBlacklisted(parentInjector, Key.get(Integer.class));
    Injector childInjector = parentInjector.createChildInjector(new AbstractModule() {

        @Override
        protected void configure() {
            OptionalBinder.newOptionalBinder(binder(), Integer.class).setDefault().toInstance(4);
        }
    });
    WeakReference<Injector> weakRef = new WeakReference<Injector>(childInjector);
    WeakKeySetUtils.assertBlacklisted(parentInjector, Key.get(Integer.class));
    // Clear the ref, GC, and ensure that we are no longer blacklisting.
    childInjector = null;
    Asserts.awaitClear(weakRef);
    WeakKeySetUtils.assertNotBlacklisted(parentInjector, Key.get(Integer.class));
}

29. InjectorGrapherDemo#main()

Project: guice
File: InjectorGrapherDemo.java
public static void main(String[] args) throws Exception {
    // TODO(phopkins): Switch to Stage.TOOL when issue 297 is fixed.
    Injector demoInjector = Guice.createInjector(Stage.DEVELOPMENT, new BackToTheFutureModule(), new MultibinderModule(), new PrivateTestModule());
    PrintWriter out = new PrintWriter(new File(args[0]), "UTF-8");
    Injector injector = Guice.createInjector(new GraphvizModule());
    GraphvizGrapher grapher = injector.getInstance(GraphvizGrapher.class);
    grapher.setOut(out);
    grapher.setRankdir("TB");
    grapher.graph(demoInjector);
}

30. OverrideModuleTest#testOverrideModuleAndPrivateModule()

Project: guice
File: OverrideModuleTest.java
public void testOverrideModuleAndPrivateModule() {
    Module exposes5 = new PrivateModule() {

        @Override
        protected void configure() {
            bind(Integer.class).toInstance(5);
            expose(Integer.class);
        }
    };
    Module binds15 = new AbstractModule() {

        @Override
        protected void configure() {
            bind(Integer.class).toInstance(15);
        }
    };
    Injector injector = Guice.createInjector(Modules.override(exposes5).with(binds15));
    assertEquals(15, injector.getInstance(Integer.class).intValue());
    Injector reverse = Guice.createInjector(Modules.override(binds15).with(exposes5));
    assertEquals(5, reverse.getInstance(Integer.class).intValue());
}

31. WeakKeySetTest#testWeakKeySet_integration()

Project: guice
File: WeakKeySetTest.java
public void testWeakKeySet_integration() {
    Injector parentInjector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(Integer.class).toInstance(4);
        }
    });
    assertNotBlacklisted(parentInjector, Key.get(String.class));
    Injector childInjector = parentInjector.createChildInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(String.class).toInstance("bar");
        }
    });
    WeakReference<Injector> weakRef = new WeakReference<Injector>(childInjector);
    assertBlacklisted(parentInjector, Key.get(String.class));
    // Clear the ref, GC, and ensure that we are no longer blacklisting.
    childInjector = null;
    awaitClear(weakRef);
    assertNotBlacklisted(parentInjector, Key.get(String.class));
}

32. TestWarmUpManager#testDag4()

Project: governator
File: TestWarmUpManager.java
@Test
public void testDag4() throws Exception {
    Injector injector = LifecycleInjector.builder().build().createInjector();
    injector.getInstance(Dag4.A.class);
    injector.getInstance(LifecycleManager.class).start();
    Recorder recorder = injector.getInstance(Recorder.class);
    LOG.info("" + recorder.getRecordings());
    LOG.info("" + recorder.getConcurrents());
    assertSingleExecution(recorder);
    Assert.assertEquals(recorder.getInterruptions().size(), 0);
    assertOrdering(recorder, "D", "E");
    assertOrdering(recorder, "C", "E");
    assertOrdering(recorder, "B", "D");
    assertOrdering(recorder, "A", "B");
}

33. TestWarmUpManager#testDag3()

Project: governator
File: TestWarmUpManager.java
@Test
public void testDag3() throws Exception {
    Injector injector = LifecycleInjector.builder().build().createInjector();
    injector.getInstance(Dag3.A.class);
    injector.getInstance(LifecycleManager.class).start();
    Recorder recorder = injector.getInstance(Recorder.class);
    LOG.info("" + recorder.getRecordings());
    LOG.info("" + recorder.getConcurrents());
    assertSingleExecution(recorder);
    assertNotConcurrent(recorder, "C", "D");
    assertNotConcurrent(recorder, "B", "D");
    assertNotConcurrent(recorder, "A", "B");
    assertNotConcurrent(recorder, "A", "C");
    Assert.assertEquals(recorder.getInterruptions().size(), 0);
    assertOrdering(recorder, "A", "C");
    assertOrdering(recorder, "C", "D");
    assertOrdering(recorder, "A", "D");
    assertOrdering(recorder, "B", "D");
}

34. TestWarmUpManager#testDag1()

Project: governator
File: TestWarmUpManager.java
@Test
public void testDag1() throws Exception {
    Injector injector = LifecycleInjector.builder().build().createInjector();
    injector.getInstance(Dag1.A.class);
    injector.getInstance(LifecycleManager.class).start();
    Recorder recorder = injector.getInstance(Recorder.class);
    LOG.info("" + recorder.getRecordings());
    LOG.info("" + recorder.getConcurrents());
    assertSingleExecution(recorder);
    assertNotConcurrent(recorder, "A", "B");
    assertNotConcurrent(recorder, "A", "C");
    Assert.assertEquals(recorder.getInterruptions().size(), 0);
    assertOrdering(recorder, "A", "B");
    assertOrdering(recorder, "A", "C");
}

35. TestWarmUpManager#testPostStart()

Project: governator
File: TestWarmUpManager.java
@Test
public void testPostStart() throws Exception {
    Injector injector = LifecycleInjector.builder().build().createInjector();
    injector.getInstance(LifecycleManager.class).start();
    injector.getInstance(Dag1.A.class);
    Recorder recorder = injector.getInstance(Recorder.class);
    LOG.info("" + recorder.getRecordings());
    LOG.info("" + recorder.getConcurrents());
    assertSingleExecution(recorder);
    assertNotConcurrent(recorder, "A", "B");
    assertNotConcurrent(recorder, "A", "C");
    Assert.assertEquals(recorder.getInterruptions().size(), 0);
    assertOrdering(recorder, "A", "B");
    assertOrdering(recorder, "A", "C");
}

36. TestFineGrainedLazySingleton#testDeadLock()

Project: governator
File: TestFineGrainedLazySingleton.java
@Test
public void testDeadLock() throws InterruptedException {
    AbstractModule module = new AbstractModule() {

        @Override
        protected void configure() {
            binder().bindScope(LazySingleton.class, LazySingletonScope.get());
            binder().bindScope(FineGrainedLazySingleton.class, FineGrainedLazySingletonScope.get());
        }
    };
    Injector injector = Guice.createInjector(module);
    // if FineGrainedLazySingleton is not used, this line will deadlock
    injector.getInstance(DeadLockTester.class);
    Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.constructorCount.get(), 1);
}

37. AbstractQueryChangesTest#setUpInjector()

Project: gerrit
File: AbstractQueryChangesTest.java
@Before
public void setUpInjector() throws Exception {
    lifecycle = new LifecycleManager();
    Injector injector = createInjector();
    lifecycle.add(injector);
    injector.injectMembers(this);
    lifecycle.start();
    db = schemaFactory.open();
    schemaCreator.create(db);
    userId = accountManager.authenticate(AuthRequest.forUser("user")).getAccountId();
    Account userAccount = db.accounts().get(userId);
    userAccount.setPreferredEmail("[email protected]");
    db.accounts().update(ImmutableList.of(userAccount));
    user = userFactory.create(userId);
    requestContext.setContext(newRequestContext(userAccount.getId()));
}

38. AbstractQueryAccountsTest#setUpInjector()

Project: gerrit
File: AbstractQueryAccountsTest.java
@Before
public void setUpInjector() throws Exception {
    lifecycle = new LifecycleManager();
    Injector injector = createInjector();
    lifecycle.add(injector);
    injector.injectMembers(this);
    lifecycle.start();
    db = schemaFactory.open();
    schemaCreator.create(db);
    Account.Id userId = createAccount("user", "User", "[email protected]", true);
    user = userFactory.create(userId);
    requestContext.setContext(newRequestContext(userId));
    currentUserInfo = gApi.accounts().id(userId.get()).get();
}

39. GerritServer#createTestInjector()

Project: gerrit
File: GerritServer.java
private static Injector createTestInjector(Daemon daemon) throws Exception {
    Injector sysInjector = get(daemon, "sysInjector");
    Module module = new FactoryModule() {

        @Override
        protected void configure() {
            bind(AccountCreator.class);
            factory(PushOneCommit.Factory.class);
            install(InProcessProtocol.module());
            install(new NoSshModule());
            install(new AsyncReceiveCommits.Module());
        }
    };
    return sysInjector.createChildInjector(module);
}

40. MetricsModuleTest#testSimpleInjection()

Project: druid
File: MetricsModuleTest.java
@Test
public void testSimpleInjection() {
    final Injector injector = Initialization.makeInjectorWithModules(GuiceInjectors.makeStartupInjector(), ImmutableList.of(new Module() {

        @Override
        public void configure(Binder binder) {
            JsonConfigProvider.bindInstance(binder, Key.get(DruidNode.class, Self.class), new DruidNode("test-inject", null, null));
        }
    }));
    final DataSourceTaskIdHolder dimensionIdHolder = new DataSourceTaskIdHolder();
    injector.injectMembers(dimensionIdHolder);
    Assert.assertNull(dimensionIdHolder.getDataSource());
    Assert.assertNull(dimensionIdHolder.getTaskId());
}

41. InitializationTest#test05MakeInjectorWithModules()

Project: druid
File: InitializationTest.java
@Test
public void test05MakeInjectorWithModules() throws Exception {
    Injector startupInjector = GuiceInjectors.makeStartupInjector();
    Injector injector = Initialization.makeInjectorWithModules(startupInjector, ImmutableList.<com.google.inject.Module>of(new com.google.inject.Module() {

        @Override
        public void configure(Binder binder) {
            JsonConfigProvider.bindInstance(binder, Key.get(DruidNode.class, Self.class), new DruidNode("test-inject", null, null));
        }
    }));
    Assert.assertNotNull(injector);
}

42. GuiceInjectorsTest#testSanity()

Project: druid
File: GuiceInjectorsTest.java
@Test
public void testSanity() {
    Injector stageOne = GuiceInjectors.makeStartupInjector();
    Module module = stageOne.getInstance(DruidSecondaryModule.class);
    Injector stageTwo = Guice.createInjector(module, new Module() {

        @Override
        public void configure(Binder binder) {
            binder.bind(String.class).toInstance("Expected String");
            JsonConfigProvider.bind(binder, "druid.emitter.", Emitter.class);
            binder.bind(CustomEmitter.class).toProvider(new CustomEmitterFactory());
        }
    });
    CustomEmitter customEmitter = stageTwo.getInstance(CustomEmitter.class);
    Assert.assertEquals("Expected String", customEmitter.getOtherValue());
}

43. ExampleApiTest#testThatInjectorAccessibleFromNinjaTestIsTheApplicationInjector()

Project: ninja
File: ExampleApiTest.java
@Test
public void testThatInjectorAccessibleFromNinjaTestIsTheApplicationInjector() {
    // this is the application guice injector
    Injector injector = getInjector();
    // We know that this service is a singleton and it provides the application initialization time.
    long serviceInitializationTime = injector.getInstance(GreetingService.class).getServiceInitializationTime();
    // provide a json with information about the application initialization time.
    String serviceInitTimeResult = ninjaTestBrowser.makeJsonRequest(getServerAddress() + "/serviceInitTime");
    //The response information must match the internal application state
    assertEquals("{\"initTime\":" + serviceInitializationTime + "}", serviceInitTimeResult);
}

44. NinjaServletListenerTest#testCallingGetInjectorMultipleTimesWorks()

Project: ninja
File: NinjaServletListenerTest.java
@Test
public void testCallingGetInjectorMultipleTimesWorks() {
    NinjaServletListener ninjaServletListener = new NinjaServletListener();
    ninjaServletListener.contextInitialized(servletContextEvent);
    Injector injector = ninjaServletListener.getInjector();
    for (int i = 0; i < 100; i++) {
        // make sure that we are getting back the very same injector all the
        // time
        assertThat(ninjaServletListener.getInjector(), equalTo(injector));
    }
}

45. NinjaServletListenerTest#testCreatingInjectorWithCustomModulesPackageWorks()

Project: ninja
File: NinjaServletListenerTest.java
@Test
public void testCreatingInjectorWithCustomModulesPackageWorks() {
    // setup stuff
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    ninjaProperties.setProperty(NinjaConstant.APPLICATION_MODULES_BASE_PACKAGE, "ninja.servlet");
    NinjaServletListener ninjaServletListener = new NinjaServletListener();
    ninjaServletListener.setNinjaProperties(ninjaProperties);
    // start the injector:
    ninjaServletListener.contextInitialized(servletContextEvent);
    // test stuff
    Injector injector = ninjaServletListener.getInjector();
    Router router = injector.getInstance((Router.class));
    //router is initialized otherwise there will be exception that routes isn't compiled
    router.getRouteFor("GET", "/");
    //validate that main application module is initialized
    Boolean mainModuleConstant = injector.getInstance(Key.get(Boolean.class, Names.named(Module.TEST_CONSTANT_NAME)));
    assertThat(mainModuleConstant, is(true));
}

46. NinjaServletListenerTest#testCreatingInjectorWithCustomNinjaPropertiesWorks()

Project: ninja
File: NinjaServletListenerTest.java
@Test
public void testCreatingInjectorWithCustomNinjaPropertiesWorks() {
    // setup stuff
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    ninjaProperties.setProperty("key!", "value!");
    NinjaServletListener ninjaServletListener = new NinjaServletListener();
    ninjaServletListener.setNinjaProperties(ninjaProperties);
    // start the injector:
    ninjaServletListener.contextInitialized(servletContextEvent);
    // test stuff
    Injector injector = ninjaServletListener.getInjector();
    NinjaProperties ninjaPropertiesFromServer = injector.getInstance(NinjaProperties.class);
    assertThat(ninjaPropertiesFromServer.get("key!"), equalTo("value!"));
    // make sure we are using the context path from the serveltcontext here
    assertThat(ninjaProperties.getContextPath(), equalTo(CONTEXT_PATH));
}

47. NinjaServletListenerTest#testCreatingInjectorWithoutContextAndOrPropertiesWorks()

Project: ninja
File: NinjaServletListenerTest.java
@Test
public void testCreatingInjectorWithoutContextAndOrPropertiesWorks() {
    NinjaServletListener ninjaServletListener = new NinjaServletListener();
    ninjaServletListener.contextInitialized(servletContextEvent);
    Injector injector = ninjaServletListener.getInjector();
    NinjaProperties ninjaProperties = injector.getInstance(NinjaProperties.class);
    // make sure we are using the context path from the serveltcontext here
    assertThat(ninjaProperties.getContextPath(), equalTo(CONTEXT_PATH));
}

48. ImplFromPropertiesFactoryTest#implementationNotAnInstanceOfTarget()

Project: ninja
File: ImplFromPropertiesFactoryTest.java
@Test
public void implementationNotAnInstanceOfTarget() {
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    ninjaProperties.setProperty("i.am.a.test.implementation", "java.lang.Object");
    Injector injector = Guice.createInjector(new BaseAndClassicModules(ninjaProperties));
    ImplFromPropertiesFactory<MockInterface> factory = new ImplFromPropertiesFactory<>(injector, ninjaProperties, "i.am.a.test.implementation", MockInterface.class, null, true, logger);
    thrown.expect(RuntimeException.class);
    MockInterface mockObject = factory.create();
}

49. ImplFromPropertiesFactoryTest#configuredImplementation()

Project: ninja
File: ImplFromPropertiesFactoryTest.java
@Test
public void configuredImplementation() {
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    ninjaProperties.setProperty("i.am.a.test.implementation", "ninja.utils.ImplFromPropertiesFactoryTest$MockInterfaceImpl");
    Injector injector = Guice.createInjector(new BaseAndClassicModules(ninjaProperties));
    ImplFromPropertiesFactory<MockInterface> factory = new ImplFromPropertiesFactory<>(injector, ninjaProperties, "i.am.a.test.implementation", MockInterface.class, null, false, logger);
    MockInterface mockObject = factory.create();
    assertThat(mockObject, instanceOf(MockInterfaceImpl.class));
}

50. ImplFromPropertiesFactoryTest#missingImplementationDeferredUntilGet()

Project: ninja
File: ImplFromPropertiesFactoryTest.java
@Test
public void missingImplementationDeferredUntilGet() {
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    ninjaProperties.setProperty("i.am.a.test.implementation", "does_not_exist");
    Injector injector = Guice.createInjector(new BaseAndClassicModules(ninjaProperties));
    // this should be okay since we want to defer the resolution until a 'get'
    ImplFromPropertiesFactory<MockInterface> factory = new ImplFromPropertiesFactory<>(injector, ninjaProperties, "i.am.a.test.implementation", MockInterface.class, null, true, logger);
    // this will not work => we expect a runtime exception with the impl missing
    thrown.expect(RuntimeException.class);
    factory.create();
}

51. ImplFromPropertiesFactoryTest#missingImplementation()

Project: ninja
File: ImplFromPropertiesFactoryTest.java
@Test
public void missingImplementation() {
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    ninjaProperties.setProperty("i.am.a.test.implementation", "does_not_exist");
    Injector injector = Guice.createInjector(new BaseAndClassicModules(ninjaProperties));
    // this will not work => we expect a runtime exception with the impl missing
    thrown.expect(RuntimeException.class);
    ImplFromPropertiesFactory<MockInterface> factory = new ImplFromPropertiesFactory<>(injector, ninjaProperties, "i.am.a.test.implementation", MockInterface.class, null, false, logger);
}

52. ImplFromPropertiesFactoryTest#defaultImplementation()

Project: ninja
File: ImplFromPropertiesFactoryTest.java
@Test
public void defaultImplementation() {
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    //ninjaProperties.setProperty("i.am.a.test.implementation", null);
    Injector injector = Guice.createInjector(new BaseAndClassicModules(ninjaProperties));
    // inner class requires $ symbol
    ImplFromPropertiesFactory<MockInterface> factory = new ImplFromPropertiesFactory<>(injector, ninjaProperties, "i.am.a.test.implementation", MockInterface.class, "ninja.utils.ImplFromPropertiesFactoryTest$MockInterfaceImpl", false, logger);
    MockInterface mockObject = factory.create();
    assertThat(mockObject, instanceOf(MockInterfaceImpl.class));
}

53. PostofficeProviderTest#verifySingletonProviderAndInstance()

Project: ninja
File: PostofficeProviderTest.java
@Test
public void verifySingletonProviderAndInstance() {
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    ninjaProperties.setProperty(PostofficeConstant.postofficeImplementation, null);
    Injector injector = Guice.createInjector(new BaseAndClassicModules(ninjaProperties));
    PostofficeProvider provider = injector.getInstance(PostofficeProvider.class);
    // cache provider should be a singleton
    assertThat(provider, sameInstance(injector.getInstance(PostofficeProvider.class)));
    assertThat(provider, sameInstance(injector.getInstance(PostofficeProvider.class)));
    Postoffice postoffice = provider.get();
    // cache should be a singleton
    assertThat(postoffice, sameInstance(provider.get()));
    assertThat(postoffice, sameInstance(injector.getInstance(Postoffice.class)));
}

54. PostofficeProviderTest#missingImplementationThrowsExceptionOnUseNotCreate()

Project: ninja
File: PostofficeProviderTest.java
@Test
public void missingImplementationThrowsExceptionOnUseNotCreate() {
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    ninjaProperties.setProperty(PostofficeConstant.postofficeImplementation, "not_existing_implementation");
    Injector injector = Guice.createInjector(new BaseAndClassicModules(ninjaProperties));
    Provider<Postoffice> provider = injector.getProvider(Postoffice.class);
    // this will not work => we expect a runtime exception...
    thrown.expect(RuntimeException.class);
    Postoffice postoffice = injector.getInstance(Postoffice.class);
}

55. PostofficeProviderTest#defaultImplementation()

Project: ninja
File: PostofficeProviderTest.java
@Test
public void defaultImplementation() {
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    ninjaProperties.setProperty(PostofficeConstant.postofficeImplementation, null);
    Injector injector = Guice.createInjector(new BaseAndClassicModules(ninjaProperties));
    PostofficeProvider postofficeProvider = injector.getInstance(PostofficeProvider.class);
    assertThat(postofficeProvider.get(), instanceOf(PostofficeMockImpl.class));
}

56. MigrationEngineProviderTest#missingImplementationThrowsExceptionOnUseNotCreate()

Project: ninja
File: MigrationEngineProviderTest.java
@Test
public void missingImplementationThrowsExceptionOnUseNotCreate() {
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    ninjaProperties.setProperty(NinjaConstant.MIGRATION_ENGINE_IMPLEMENTATION, "not_existing_implementation");
    Injector injector = Guice.createInjector(new BaseAndClassicModules(ninjaProperties));
    Provider<MigrationEngine> provider = injector.getProvider(MigrationEngine.class);
    // this will not work => we expect a runtime exception...
    thrown.expect(RuntimeException.class);
    MigrationEngine migrationEngine = injector.getInstance(MigrationEngine.class);
}

57. MigrationEngineProviderTest#defaultImplementation()

Project: ninja
File: MigrationEngineProviderTest.java
@Test
public void defaultImplementation() {
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    ninjaProperties.setProperty(NinjaConstant.MIGRATION_ENGINE_IMPLEMENTATION, null);
    Injector injector = Guice.createInjector(new BaseAndClassicModules(ninjaProperties));
    Provider<MigrationEngine> provider = injector.getProvider(MigrationEngine.class);
    assertThat(provider.get(), instanceOf(MigrationEngineFlyway.class));
}

58. LifecycleSupportTest#providedSingletonDisposableShouldBeDisposed()

Project: ninja
File: LifecycleSupportTest.java
@Test
public void providedSingletonDisposableShouldBeDisposed() {
    Injector injector = createInjector(new AbstractModule() {

        @Override
        protected void configure() {
        }

        @Provides
        @Singleton
        public MockSingletonService provide() {
            return new MockSingletonService();
        }
    });
    start(injector);
    stop(injector);
    assertThat(MockSingletonService.disposed, equalTo(1));
}

59. LifecycleSupportTest#providedSingletonStartableShouldBeStarted()

Project: ninja
File: LifecycleSupportTest.java
@Test
public void providedSingletonStartableShouldBeStarted() {
    Injector injector = createInjector(new AbstractModule() {

        @Override
        protected void configure() {
        }

        @Provides
        @Singleton
        public MockSingletonService provide() {
            return new MockSingletonService();
        }
    });
    start(injector);
    assertThat(MockSingletonService.started, equalTo(1));
}

60. CacheProviderTest#verifySingletonProviderAndInstance()

Project: ninja
File: CacheProviderTest.java
@Test
public void verifySingletonProviderAndInstance() {
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    ninjaProperties.setProperty(NinjaConstant.CACHE_IMPLEMENTATION, CacheMockImpl.class.getCanonicalName());
    Injector injector = Guice.createInjector(new BaseAndClassicModules(ninjaProperties));
    CacheProvider cacheProvider = injector.getInstance(CacheProvider.class);
    // cache provider should be a singleton
    assertThat(cacheProvider, sameInstance(injector.getInstance(CacheProvider.class)));
    assertThat(cacheProvider, sameInstance(injector.getInstance(CacheProvider.class)));
    Cache cache = cacheProvider.get();
    // cache should be a singleton
    assertThat(cache, sameInstance(cacheProvider.get()));
    assertThat(cache, sameInstance(injector.getInstance(Cache.class)));
}

61. CacheProviderTest#missingImplementationThrowsExceptionOnUseNotCreate()

Project: ninja
File: CacheProviderTest.java
@Test
public void missingImplementationThrowsExceptionOnUseNotCreate() {
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    ninjaProperties.setProperty(NinjaConstant.CACHE_IMPLEMENTATION, "not_existing_implementation");
    Injector injector = Guice.createInjector(new BaseAndClassicModules(ninjaProperties));
    Provider<Cache> provider = injector.getProvider(Cache.class);
    // this will not work => we expect a runtime exception...
    thrown.expect(RuntimeException.class);
    Cache cache = injector.getInstance(Cache.class);
}

62. CacheProviderTest#configuredImplementation()

Project: ninja
File: CacheProviderTest.java
@Test
public void configuredImplementation() {
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    ninjaProperties.setProperty(NinjaConstant.CACHE_IMPLEMENTATION, CacheMemcachedImpl.class.getName());
    // just a dummy to test that loading works
    ninjaProperties.setProperty(NinjaConstant.MEMCACHED_HOST, "127.0.0.1:1234");
    Injector injector = Guice.createInjector(new BaseAndClassicModules(ninjaProperties));
    Provider<Cache> cacheProvider = injector.getProvider(Cache.class);
    assertThat(cacheProvider.get(), instanceOf(CacheMemcachedImpl.class));
}

63. CacheProviderTest#defaultImplementation()

Project: ninja
File: CacheProviderTest.java
@Test
public void defaultImplementation() {
    NinjaPropertiesImpl ninjaProperties = new NinjaPropertiesImpl(NinjaMode.test);
    ninjaProperties.setProperty(NinjaConstant.CACHE_IMPLEMENTATION, null);
    Injector injector = Guice.createInjector(new BaseAndClassicModules(ninjaProperties));
    CacheProvider cacheProvider = injector.getInstance(CacheProvider.class);
    assertThat(cacheProvider.get(), instanceOf(CacheEhCacheImpl.class));
}

64. BodyParserEnginePostTest#setUp()

Project: ninja
File: BodyParserEnginePostTest.java
@Before
public void setUp() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(NinjaProperties.class).toInstance(new NinjaPropertiesImpl(NinjaMode.test));
            Multibinder<ParamParser> parsersBinder = Multibinder.newSetBinder(binder(), ParamParser.class);
            parsersBinder.addBinding().to(NeedingInjectionParamParser.class);
        }
    });
    validation = new ValidationImpl();
    Mockito.when(this.context.getValidation()).thenReturn(this.validation);
    bodyParserEnginePost = injector.getInstance(BodyParserEnginePost.class);
}

65. GuiceIntegrationTest#testFromGuice()

Project: modelmapper
File: GuiceIntegrationTest.java
public void testFromGuice() {
    final Dest dest = new Dest();
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(Dest.class).toInstance(dest);
        }
    });
    Provider<?> provider = GuiceIntegration.fromGuice(injector);
    ModelMapper mapper = new ModelMapper();
    mapper.getConfiguration().setProvider(provider);
    assertEquals(mapper.map(new Source(), Dest.class), dest);
}

66. Importer#main()

Project: mail-importer
File: Importer.java
/**
   * Main entry point for running {@code Importer} as a stand-alone application.
   * Commandline options can be found in
   * {@link to.lean.tools.gmail.importer.CommandLineArguments}.
   *
   * @param args the command line arguments
   * @throws MessagingException if there is a problem reading from the local
   *     store
   * @throws IOException if there is a problem with the Gmail connection
   */
public static void main(String[] args) throws MessagingException, IOException {
    CommandLineArguments commandLineArguments = new CommandLineArguments();
    CmdLineParser commandLine = new CmdLineParser(commandLineArguments);
    try {
        commandLine.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        commandLine.printUsage(System.err);
        System.exit(1);
    }
    Injector injector = Guice.createInjector(new FlagsModule(commandLineArguments), new ThunderbirdModule(), new GmailServiceModule());
    Importer importer = injector.getInstance(Importer.class);
    importer.importMail();
}

67. HealthCheckResourceTest#buildAdminResourcesContainer()

Project: karyon
File: HealthCheckResourceTest.java
private AdminResourcesContainer buildAdminResourcesContainer(final HealthCheckHandler healthCheckHandler) throws Exception {
    AdminResourcesContainer container = new AdminResourcesContainer();
    final Field injectorField = AdminResourcesContainer.class.getDeclaredField("appInjector");
    final Injector appInjector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(HealthCheckHandler.class).toInstance(healthCheckHandler);
        }
    });
    injectorField.setAccessible(true);
    injectorField.set(container, appInjector);
    return container;
}

68. HealthCheckResourceTest#buildAdminResourcesContainer()

Project: karyon
File: HealthCheckResourceTest.java
private AdminResourcesContainer buildAdminResourcesContainer(final HealthCheckHandler healthCheckHandler) throws Exception {
    AdminResourcesContainer container = new AdminResourcesContainer();
    final Field injectorField = AdminResourcesContainer.class.getDeclaredField("appInjector");
    final Injector appInjector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(HealthCheckHandler.class).toInstance(healthCheckHandler);
            bind(HealthCheckInvocationStrategy.class).to(SyncHealthCheckInvocationStrategy.class);
        }
    });
    injectorField.setAccessible(true);
    injectorField.set(container, appInjector);
    return container;
}

69. TestMBeanModule#testAnnotation()

Project: jmxutils
File: TestMBeanModule.java
@Test
public void testAnnotation() throws IntrospectionException, InstanceNotFoundException, IOException, ReflectionException, MalformedObjectNameException, MBeanRegistrationException {
    final ObjectName objectName = Util.getUniqueObjectName();
    Injector injector = Guice.createInjector(PRODUCTION, new MBeanModule(), new AbstractModule() {

        @Override
        protected void configure() {
            binder().requireExplicitBindings();
            binder().disableCircularProxies();
            bind(SimpleObject.class).annotatedWith(TestAnnotation.class).toInstance(new SimpleObject());
            bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
            ExportBinder.newExporter(binder()).export(SimpleObject.class).annotatedWith(TestAnnotation.class).as(objectName.getCanonicalName());
        }
    });
    MBeanServer server = injector.getInstance(MBeanServer.class);
    Assert.assertNotNull(server.getMBeanInfo(objectName));
    server.unregisterMBean(objectName);
}

70. TestMBeanModule#testGeneratedNames()

Project: jmxutils
File: TestMBeanModule.java
@Test
public void testGeneratedNames() throws IOException, IntrospectionException, InstanceNotFoundException, ReflectionException, MalformedObjectNameException, MBeanRegistrationException {
    final ObjectName name = new ObjectName(generatedNameOf(SimpleObject.class));
    Injector injector = Guice.createInjector(PRODUCTION, new MBeanModule(), new AbstractModule() {

        @Override
        protected void configure() {
            binder().requireExplicitBindings();
            binder().disableCircularProxies();
            bind(SimpleObject.class).asEagerSingleton();
            bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
            ExportBinder.newExporter(binder()).export(SimpleObject.class).withGeneratedName();
        }
    });
    MBeanServer server = injector.getInstance(MBeanServer.class);
    Assert.assertNotNull(server.getMBeanInfo(name));
    server.unregisterMBean(name);
}

71. TestMBeanModule#testBasic()

Project: jmxutils
File: TestMBeanModule.java
@Test
public void testBasic() throws IOException, IntrospectionException, InstanceNotFoundException, ReflectionException, MalformedObjectNameException, MBeanRegistrationException {
    final ObjectName name = Util.getUniqueObjectName();
    Injector injector = Guice.createInjector(PRODUCTION, new MBeanModule(), new AbstractModule() {

        @Override
        protected void configure() {
            binder().requireExplicitBindings();
            binder().disableCircularProxies();
            bind(SimpleObject.class).asEagerSingleton();
            bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
            ExportBinder.newExporter(binder()).export(SimpleObject.class).as(name.getCanonicalName());
        }
    });
    MBeanServer server = injector.getInstance(MBeanServer.class);
    Assert.assertNotNull(server.getMBeanInfo(name));
    server.unregisterMBean(name);
}

72. TestMBeanModule#testExportedInDevelopmentStageToo()

Project: jmxutils
File: TestMBeanModule.java
@Test
public void testExportedInDevelopmentStageToo() throws IntrospectionException, InstanceNotFoundException, ReflectionException {
    final ObjectName name = Util.getUniqueObjectName();
    Injector injector = Guice.createInjector(new MBeanModule(), new AbstractModule() {

        @Override
        protected void configure() {
            binder().requireExplicitBindings();
            binder().disableCircularProxies();
            bind(SimpleObject.class).asEagerSingleton();
            bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
            ExportBinder.newExporter(binder()).export(SimpleObject.class).as(name.getCanonicalName());
        }
    });
    MBeanServer server = injector.getInstance(MBeanServer.class);
    Assert.assertNotNull(server.getMBeanInfo(name));
}

73. JmxTransformer#main()

Project: jmxtrans
File: JmxTransformer.java
public static void main(String[] args) throws Exception {
    JmxTransConfiguration configuration = new JCommanderArgumentParser().parseOptions(args);
    if (configuration.isHelp()) {
        return;
    }
    ClassLoaderEnricher enricher = new ClassLoaderEnricher();
    for (File jar : configuration.getAdditionalJars()) {
        enricher.add(jar);
    }
    Injector injector = JmxTransModule.createInjector(configuration);
    JmxTransformer transformer = injector.getInstance(JmxTransformer.class);
    // Start the process
    transformer.doMain();
}

74. Bootstrap#createFairy()

Project: jfairy
File: Bootstrap.java
public static Fairy createFairy(DataMaster dataMaster, Locale locale, Random random) {
    FairyModule fairyModule = getFairyModuleForLocale(dataMaster, locale, random);
    Injector injector = Guice.createInjector(fairyModule);
    FairyFactory fairyFactory = injector.getInstance(FairyFactory.class);
    return fairyFactory.createFairy();
}

75. GuiceStepsFactoryBehaviour#assertThatStepsWithMissingDependenciesCannotBeCreated()

Project: jbehave-core
File: GuiceStepsFactoryBehaviour.java
@Test(expected = CreationException.class)
public void assertThatStepsWithMissingDependenciesCannotBeCreated() throws NoSuchFieldException, IllegalAccessException {
    Injector parent = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(FooStepsWithDependency.class);
        }
    });
    AbstractStepsFactory factory = new GuiceStepsFactory(new MostUsefulConfiguration(), parent);
    // When
    factory.createCandidateSteps();
// Then ... expected exception is thrown        
}

76. GuiceStepsFactoryBehaviour#assertThatStepsWithStepsWithDependencyCanBeCreated()

Project: jbehave-core
File: GuiceStepsFactoryBehaviour.java
@Test
public void assertThatStepsWithStepsWithDependencyCanBeCreated() throws NoSuchFieldException, IllegalAccessException {
    Injector parent = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(Integer.class).toInstance(42);
            bind(FooStepsWithDependency.class).in(Scopes.SINGLETON);
        }
    });
    // When
    AbstractStepsFactory factory = new GuiceStepsFactory(new MostUsefulConfiguration(), parent);
    List<CandidateSteps> steps = factory.createCandidateSteps();
    // Then
    assertFooStepsFound(steps);
    assertEquals(42, (int) ((FooStepsWithDependency) stepsInstance(steps.get(0))).integer);
}

77. GuiceStepsFactoryBehaviour#assertThatStepsCanBeCreated()

Project: jbehave-core
File: GuiceStepsFactoryBehaviour.java
@Test
public void assertThatStepsCanBeCreated() throws NoSuchFieldException, IllegalAccessException {
    // Given
    Injector parent = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(FooSteps.class).in(Scopes.SINGLETON);
        }
    });
    AbstractStepsFactory factory = new GuiceStepsFactory(new MostUsefulConfiguration(), parent);
    // When
    List<CandidateSteps> steps = factory.createCandidateSteps();
    // Then 
    assertFooStepsFound(steps);
}

78. RpcTest#setUp()

Project: incubator-wave
File: RpcTest.java
@Override
public void setUp() throws Exception {
    super.setUp();
    SessionManager sessionManager = Mockito.mock(SessionManager.class);
    /*
     * NOTE: Specifying port zero (0) causes the OS to select a random port.
     * This allows the test to run without clashing with any potentially in-use port.
     */
    server = new ServerRpcProvider(new InetSocketAddress[] { new InetSocketAddress("localhost", 0) }, new String[] { "./war" }, sessionManager, null, null, false, null, null, MoreExecutors.sameThreadExecutor());
    final Map<String, Object> props = new HashMap<>();
    props.put("network.websocket_max_idle_time", 0);
    props.put("network.websocket_max_message_size", 2);
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(ServerRpcProvider.class).toInstance(server);
            bind(Config.class).toInstance(ConfigFactory.parseMap(props));
        }
    });
    server.startWebSocketServer(injector);
}

79. BalanceBooks#init()

Project: incubator-tephra
File: BalanceBooks.java
/**
   * Sets up common resources required by all clients.
   */
public void init() throws IOException {
    Injector injector = Guice.createInjector(new ConfigModule(conf), new ZKModule(), new DiscoveryModules().getDistributedModules(), new TransactionModules().getDistributedModules(), new TransactionClientModule());
    zkClient = injector.getInstance(ZKClientService.class);
    zkClient.startAndWait();
    txClient = injector.getInstance(TransactionServiceClient.class);
    createTableIfNotExists(conf, TABLE, new byte[][] { FAMILY });
    conn = HConnectionManager.createConnection(conf);
}

80. TransactionExecutorTest#setup()

Project: incubator-tephra
File: TransactionExecutorTest.java
@BeforeClass
public static void setup() throws IOException {
    final Configuration conf = new Configuration();
    conf.set(TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES, DefaultSnapshotCodec.class.getName());
    conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_DIR, tmpFolder.newFolder().getAbsolutePath());
    Injector injector = Guice.createInjector(new ConfigModule(conf), new DiscoveryModules().getInMemoryModules(), Modules.override(new TransactionModules().getInMemoryModules()).with(new AbstractModule() {

        @Override
        protected void configure() {
            TransactionManager txManager = new TransactionManager(conf);
            txManager.startAndWait();
            bind(TransactionManager.class).toInstance(txManager);
            bind(TransactionSystemClient.class).to(DummyTxClient.class).in(Singleton.class);
        }
    }));
    txClient = (DummyTxClient) injector.getInstance(TransactionSystemClient.class);
    factory = injector.getInstance(TransactionExecutorFactory.class);
}

81. TransactionContextTest#setup()

Project: incubator-tephra
File: TransactionContextTest.java
@BeforeClass
public static void setup() throws IOException {
    final Configuration conf = new Configuration();
    conf.set(TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES, SnapshotCodecV4.class.getName());
    conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_DIR, tmpFolder.newFolder().getAbsolutePath());
    Injector injector = Guice.createInjector(new ConfigModule(conf), new DiscoveryModules().getInMemoryModules(), Modules.override(new TransactionModules().getInMemoryModules()).with(new AbstractModule() {

        @Override
        protected void configure() {
            TransactionManager txManager = new TransactionManager(conf);
            txManager.startAndWait();
            bind(TransactionManager.class).toInstance(txManager);
            bind(TransactionSystemClient.class).to(DummyTxClient.class).in(Singleton.class);
        }
    }));
    txClient = (DummyTxClient) injector.getInstance(TransactionSystemClient.class);
}

82. TransactionServiceMain#start()

Project: incubator-tephra
File: TransactionServiceMain.java
/**
   * Invoked by jsvc to start the program.
   */
public void start() throws Exception {
    Injector injector = Guice.createInjector(new ConfigModule(conf), new ZKModule(), new DiscoveryModules().getDistributedModules(), new TransactionModules().getDistributedModules(), new TransactionClientModule());
    ZKClientService zkClientService = injector.getInstance(ZKClientService.class);
    zkClientService.startAndWait();
    // start a tx server
    txService = injector.getInstance(TransactionService.class);
    try {
        LOG.info("Starting {}", getClass().getSimpleName());
        txService.startAndWait();
    } catch (Exception e) {
        System.err.println("Failed to start service: " + e.getMessage());
    }
}

83. MyApp#main()

Project: incubator-s4
File: MyApp.java
public static void main(String[] args) {
    Injector injector = Guice.createInjector(new Module());
    MyApp myApp = injector.getInstance(MyApp.class);
    Sender sender = injector.getInstance(SenderImpl.class);
    ReceiverImpl receiver = injector.getInstance(ReceiverImpl.class);
    // myApp.setCommLayer(sender, receiver);
    myApp.init();
    myApp.start();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    myApp.close();
// receiver.close();
}

84. TestEDSL#test()

Project: incubator-s4
File: TestEDSL.java
@Test
public void test() throws Exception {
    Injector injector = Guice.createInjector(new BaseModule(Resources.getResource("default.s4.base.properties").openStream(), "cluster1"), new DefaultCommModule(Resources.getResource("default.s4.comm.properties").openStream()), new DefaultCoreModule(Resources.getResource("default.s4.core.properties").openStream()));
    MyApp myApp = injector.getInstance(MyApp.class);
    /* Normally. the container will handle this but this is just a test. */
    myApp.init();
    myApp.start();
    myApp.close();
}

85. MultithreadingTest#testSynchronization()

Project: incubator-s4
File: MultithreadingTest.java
/*
     * We inject one event and fire one onTime() event, both should be synchronized (not running in parallel)
     */
@Test
public void testSynchronization() throws IOException, InterruptedException {
    Injector injector = Guice.createInjector(new MockCommModule(), new MockCoreModule(), new AppModule(getClass().getClassLoader()));
    TestApp app = injector.getInstance(TestApp.class);
    // One for the event, another for the timer
    app.count = 2;
    app.init();
    app.start();
    Event event = new Event();
    event.setStreamId(STREAM_NAME);
    app.testStream.receiveEvent(event);
    /*
         * This must raise a timeout, since the onTime() event is blocked waiting for the onEvent() call to finish. If
         * it completes before the timeout, it means onEvent() and onTime() weren't synchronized
         */
    assertFalse("The timer wasn't synchronized with the event", app.latch.await(2, TimeUnit.SECONDS));
}

86. SmoothieContainerImpl#register()

Project: hudson-2.x
File: SmoothieContainerImpl.java
public void register(final PluginWrapper plugin) {
    assert plugin != null;
    if (log.isTraceEnabled()) {
        log.trace("Registering plugin: {}", plugin.getShortName());
    }
    // Don't allow re-registration of plugins
    if (injectors.containsKey(plugin)) {
        throw new IllegalStateException("Plugin already registered");
    }
    Injector injector = createInjector(new PluginModule(plugin));
    injectors.put(plugin, injector);
}

87. SmoothieContainerImpl#createInjector()

Project: hudson-2.x
File: SmoothieContainerImpl.java
private Injector createInjector(final Module... modules) {
    assert modules != null;
    Injector injector = Guice.createInjector(new WireModule(modules));
    if (log.isTraceEnabled()) {
        log.trace("Created injector: {} w/bindings:", OID.get(injector));
        for (Map.Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet()) {
            log.trace("  {} -> {}", entry.getKey(), entry.getValue());
        }
    }
    return injector;
}

88. HarmonyServer#setup()

Project: ha-bridge
File: HarmonyServer.java
public static HarmonyServer setup(BridgeSettingsDescriptor bridgeSettings, Boolean harmonyDevMode, NamedIP theHarmonyAddress) throws Exception {
    if (!bridgeSettings.isValidHarmony() && harmonyDevMode) {
        return new HarmonyServer(theHarmonyAddress);
    }
    Injector injector = null;
    if (!harmonyDevMode)
        injector = Guice.createInjector(new HarmonyClientModule());
    HarmonyServer mainObject = new HarmonyServer(theHarmonyAddress);
    if (!harmonyDevMode)
        injector.injectMembers(mainObject);
    mainObject.execute(bridgeSettings, harmonyDevMode);
    return mainObject;
}

89. Java8LanguageFeatureBindingTest#testBinding_toProvider_lambda()

Project: guice
File: Java8LanguageFeatureBindingTest.java
public void testBinding_toProvider_lambda() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            AtomicInteger i = new AtomicInteger();
            bind(String.class).toProvider(() -> "Hello" + i.incrementAndGet());
        }
    });
    assertEquals("Hello1", injector.getInstance(String.class));
    assertEquals("Hello2", injector.getInstance(String.class));
}

90. Java8LanguageFeatureBindingTest#testProvider_usingJdk8Features()

Project: guice
File: Java8LanguageFeatureBindingTest.java
public void testProvider_usingJdk8Features() {
    try {
        Guice.createInjector(new AbstractModule() {

            @Override
            protected void configure() {
                bind(String.class).toProvider(StringProvider.class);
            }
        });
        fail();
    } catch (CreationException expected) {
    }
    UUID uuid = UUID.randomUUID();
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(UUID.class).toInstance(uuid);
            bind(String.class).toProvider(StringProvider.class);
        }
    });
    assertEquals(uuid.toString(), injector.getInstance(String.class));
}

91. Java8LanguageFeatureBindingTest#testProviderMethod_containingLambda_throwingException()

Project: guice
File: Java8LanguageFeatureBindingTest.java
public void testProviderMethod_containingLambda_throwingException() throws Exception {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
        }

        @Provides
        public Callable<String> provideCallable() {
            if (Boolean.parseBoolean("false")) {
                // avoid dead code warnings
                return () -> "foo";
            } else {
                throw new RuntimeException("foo");
            }
        }
    });
    try {
        injector.getInstance(new Key<Callable<String>>() {
        });
    } catch (ProvisionException expected) {
        assertTrue(expected.getCause() instanceof RuntimeException);
        assertEquals("foo", expected.getCause().getMessage());
    }
}

92. Java8LanguageFeatureBindingTest#testProviderMethod_returningLambda()

Project: guice
File: Java8LanguageFeatureBindingTest.java
public void testProviderMethod_returningLambda() throws Exception {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
        }

        @Provides
        public Callable<String> provideCallable() {
            return () -> "foo";
        }
    });
    Callable<String> callable = injector.getInstance(new Key<Callable<String>>() {
    });
    assertEquals("foo", callable.call());
}

93. Java8LanguageFeatureBindingTest#testBinding_lambdaToInterface()

Project: guice
File: Java8LanguageFeatureBindingTest.java
// Some of these tests are kind of weird.
// See https://github.com/google/guice/issues/757 for more on why they exist.
public void testBinding_lambdaToInterface() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(new TypeLiteral<Predicate<Object>>() {
            }).toInstance( o -> o != null);
        }
    });
    Predicate<Object> predicate = injector.getInstance(new Key<Predicate<Object>>() {
    });
    assertTrue(predicate.test(new Object()));
    assertFalse(predicate.test(null));
}

94. DefaultMethodInterceptionTest#testInterception_ofAllMethodsOnType_interceptsInheritedDefaultMethod()

Project: guice
File: DefaultMethodInterceptionTest.java
public void testInterception_ofAllMethodsOnType_interceptsInheritedDefaultMethod() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bindInterceptor(Matchers.subclassesOf(BazImpl.class), Matchers.any(), interceptor);
            bind(Baz.class).to(BazImpl.class);
        }
    });
    Baz baz = injector.getInstance(Baz.class);
    assertEquals("Baz", baz.doSomething());
    assertEquals("BazImpl", baz.doSomethingElse());
    assertEquals(2, interceptedCallCount.get());
}

95. DefaultMethodInterceptionTest#testInterception_ofAllMethodsOnType()

Project: guice
File: DefaultMethodInterceptionTest.java
public void testInterception_ofAllMethodsOnType() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bindInterceptor(Matchers.subclassesOf(Baz.class), Matchers.any(), interceptor);
            bind(Baz.class).to(BazImpl.class);
        }
    });
    Baz baz = injector.getInstance(Baz.class);
    assertEquals("Baz", baz.doSomething());
    assertEquals("BazImpl", baz.doSomethingElse());
    assertEquals(2, interceptedCallCount.get());
}

96. DefaultMethodInterceptionTest#testInterceptedDefaultMethod_whenParentClassDefinesInterceptedMethod()

Project: guice
File: DefaultMethodInterceptionTest.java
public void testInterceptedDefaultMethod_whenParentClassDefinesInterceptedMethod() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bindInterceptor(Matchers.any(), Matchers.annotatedWith(InterceptMe.class), interceptor);
            bind(Foo.class).to(InheritingFoo2.class);
        }
    });
    // the concrete implementation that wins is not annotated
    Foo foo = injector.getInstance(Foo.class);
    assertEquals("BaseClass2", foo.defaultMethod());
    assertEquals(1, callCount.get());
    assertEquals(1, interceptedCallCount.get());
}

97. DefaultMethodInterceptionTest#testInterceptedDefaultMethod_whenParentClassDefinesNonInterceptedMethod()

Project: guice
File: DefaultMethodInterceptionTest.java
public void testInterceptedDefaultMethod_whenParentClassDefinesNonInterceptedMethod() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bindInterceptor(Matchers.any(), Matchers.annotatedWith(InterceptMe.class), interceptor);
            bind(Foo.class).to(InheritingFoo.class);
        }
    });
    // the concrete implementation that wins is not annotated
    Foo foo = injector.getInstance(Foo.class);
    assertEquals("BaseClass", foo.defaultMethod());
    assertEquals(1, callCount.get());
    assertEquals(0, interceptedCallCount.get());
}

98. DefaultMethodInterceptionTest#testInterceptedDefaultMethod_calledByAnotherMethod()

Project: guice
File: DefaultMethodInterceptionTest.java
public void testInterceptedDefaultMethod_calledByAnotherMethod() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bindInterceptor(Matchers.any(), Matchers.annotatedWith(InterceptMe.class), interceptor);
        }
    });
    NonOverridingFoo foo = injector.getInstance(NonOverridingFoo.class);
    assertEquals("NonOverriding-Foo", foo.methodCallingDefault());
    assertEquals(1, callCount.get());
    assertEquals(1, interceptedCallCount.get());
}

99. DefaultMethodInterceptionTest#testInterceptedDefaultMethod()

Project: guice
File: DefaultMethodInterceptionTest.java
public void testInterceptedDefaultMethod() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bindInterceptor(Matchers.any(), Matchers.annotatedWith(InterceptMe.class), interceptor);
            bind(Foo.class).to(NonOverridingFoo.class);
        }
    });
    Foo foo = injector.getInstance(Foo.class);
    assertEquals("Foo", foo.defaultMethod());
    assertEquals(1, callCount.get());
    assertEquals(1, interceptedCallCount.get());
}

100. CheckedProviderMethodsModuleTest#testWithThrownException()

Project: guice
File: CheckedProviderMethodsModuleTest.java
public void testWithThrownException() {
    TestModule testModule = new TestModule();
    Injector injector = Guice.createInjector(testModule);
    RpcProvider<Float> provider = injector.getInstance(Key.get(rpcProviderOfFloat));
    try {
        provider.get();
        fail();
    } catch (RemoteException e) {
        fail();
    } catch (BindException e) {
    }
}