@Test public void missingLanguageThrowsExceptionByBootstrap() throws Exception { // bad configuration file will throw exception during ninja bootstrap NinjaVertx standalone = new NinjaVertx() .externalConfigurationPath("conf/vertx.missinglang.conf") .port(randomPort); try { standalone.start(); fail("start() should have thrown exception"); } catch (CreationException e) { assertThat(e.getMessage(), containsString("not retrieve application languages from ninjaProperties")); } finally { standalone.shutdown(); } }
@Test(expected = CreationException.class) public void testFailOnConstructor() throws Exception { final Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { ScopedProxyBinder.using(binder()) .andConstructionStrategy( ConstructionStrategies.FAIL_ON_CONSTRUCTOR) .bind(ConcreteSampleClassWithCtor.class) .to(ConcreteSampleClassWithCtor.class); } }); injector.getInstance(ConcreteSampleClassWithCtor.class); }
@Test public void testIllegalMethods() throws Exception { try { Guice.createInjector( Stage.PRODUCTION, new Module() { @Override public void configure(Binder binder) { binder.bind(IllegalInstance.class).in(Scopes.SINGLETON); } }, new LifeCycleModule()); Assert.fail(); } catch (CreationException dummy) { // correct behavior } }
@Test public void shouldThrowGugisExceptionWhenImplementationsNotFound() { try { // fail fast, Guice injector will not be created at all Guice.createInjector(new GugisModule()); Assert.fail("There should be an exception thrown by Gugis validation"); } catch (CreationException e) { // the following errors should be detected: // 1) ReportServiceComposite does not have any implementations at all Assert.assertTrue(e.getCause().getMessage().contains("No implementations found for " + ReportServiceComposite.class)); // 2) AggregatorServiceComposite does not have @Primary implementations Assert.assertTrue(e.getCause().getMessage().contains("Composite component " + AggregatorServiceComposite.class + " methods [public void aggregate()] marked with @Propagate(propagation = Propagation.PRIMARY) but no primary implementations found")); // 3) SplitterServiceComposite does not have @Secondary implementations Assert.assertTrue(e.getCause().getMessage().contains("Composite component " + SplitterServiceComposite.class + " methods [public void split()] marked with @Propagate(propagation = Propagation.SECONDARY) but no secondary implementations found")); } catch (Throwable t) { Assert.fail("CreationException expected but got " + t.getClass()); } }
public static void main(String... args) { WSFRealtimeMain m = new WSFRealtimeMain(); ArgumentParser parser = ArgumentParsers.newArgumentParser("wsf-gtfsrealtime"); parser.description("Produces a GTFS-realtime feed from the Washington State Ferries API"); parser.addArgument("--" + ARG_CONFIG_FILE).type(File.class).help("configuration file path"); Namespace parsedArgs; try { parsedArgs = parser.parseArgs(args); File configFile = parsedArgs.get(ARG_CONFIG_FILE); m.run(configFile); } catch (CreationException | ConfigurationException | ProvisionException e) { _log.error("Error in startup:", e); System.exit(-1); } catch (ArgumentParserException ex) { parser.handleError(ex); } }
private void foundGbeForTheFirstTime(final Class<? extends Module> gbeClass) { Injector result = BOGUS_INJECTOR; try { Module gbeInstance = createGbeInstanceFromClass(gbeClass); Injector injector = Guice.createInjector(gbeInstance); ensureBasicBindingsExist(injector, gbeClass); // Get a members injector for the test class first so that we fail fast if there are missing // bindings instead of running the main getMembersInjectorForTest(gbeClass, injector); callGbeMainIfBound(injector); // We don't actually use the test wrapper here, but we make sure we can // get an instance (i.e. we fail fast). buildTestWrapperInstance(injector); result = injector; } catch (CreationException e) { if (e.getMessage().contains("No scope is bound to " + TestScoped.class.getName())) { throwAppropriateExceptionOnMissingRequiredBindings(gbeClass); } else { throw e; } } finally { // This is in the finally block to ensure that BOGUS_INJECTOR // is put in the map if things go bad. universe.gbeClassToInjectorMap.put(gbeClass, result); } }
public void testCannotInterceptBareBinding() { Module module = new AbstractModule() { @Override protected void configure() { bind(ArrayList.class); } }; Module built = new InterceptingBindingsBuilder() .intercept(ArrayList.class) .install(module) .build(); try { Guice.createInjector(built); fail(); } catch(CreationException expected) { } }
public void testAllInterceptedKeysMustBeBound() { Module module = new AbstractModule() { @Override protected void configure() { bind(ProvisionInterceptor.class).toInstance(failingInterceptor); } }; Module built = new InterceptingBindingsBuilder() .intercept(ArrayList.class) .install(module) .build(); try { Guice.createInjector(built); fail(); } catch(CreationException expected) { } }
/** * Like {@link #testFailsInjectionBeforeRunningGuiceBerryEnvMain_MissingTestBinding()} * except for bindings that are missing in the test wrapper. */ @Test public void testFailsInjectionBeforeRunningGuiceBerryEnvMain_MissingWrapperBinding() { GuiceBerryEnvSelector guiceBerryEnvSelector = DefaultEnvSelector.of(MyGuiceBerryEnvWithGuiceBerryEnvMainThatThrowsAndWithATestWrapperWithAMissingBinding.class); TestDescription testDescription = new TestDescription(new MyTest(), "some test case"); GuiceBerryUniverse.TestCaseScaffolding testCaseScaffolding = new GuiceBerryUniverse.TestCaseScaffolding(testDescription, guiceBerryEnvSelector, universe); try { testCaseScaffolding.runBeforeTest(); Assert.fail("The test has an unsatisfied injection, and the GuiceBerryEnvMain " + "throws an Exception. Either of these reasons should have prevented the " + "test from having gotten here."); } catch (MyGuiceBerryEnvWithGuiceBerryEnvMainThatThrows.GuiceBerryEnvMainWasExecutedException toThrow) { throw toThrow; } catch (CreationException expected) {} testCaseScaffolding.runAfterTest(); }
private void addMessageIfInformative(LinkedList<String> messages, Throwable cause) { if (cause instanceof ProvisionException) { // This technical exception is hidden. Only its causes should be shown. return; } if (cause instanceof ConfigurationException) { // A missing setting in settings.properties can cause this exception. ConfigurationException configurationException = (ConfigurationException) cause; addClearifiedErrorMessages(messages, configurationException.getErrorMessages()); return; } if (cause instanceof CreationException) { // A missing setting in settings.properties can cause this exception. CreationException creationException = (CreationException) cause; addClearifiedErrorMessages(messages, creationException.getErrorMessages()); return; } messages.add(cause.getMessage()); }
public void testFailingScanner() { try { Guice.createInjector(new SomeModule(), FailingScanner.module()); fail(); } catch (CreationException expected) { Message m = Iterables.getOnlyElement(expected.getErrorMessages()); assertEquals( "An exception was caught and reported. Message: Failing in the scanner.", m.getMessage()); assertEquals(IllegalStateException.class, m.getCause().getClass()); ElementSource source = (ElementSource) Iterables.getOnlyElement(m.getSources()); assertEquals( SomeModule.class.getName(), Iterables.getOnlyElement(source.getModuleClassNames())); assertEquals( String.class.getName() + " " + SomeModule.class.getName() + ".aString()", source.toString()); } }
public void testMultipleBindingAnnotations() { try { Guice.createInjector(new AbstractModule() { @Override protected void configure() {} @Provides @Named("A") @Blue public String provideString() { return "a"; } }); fail(); } catch (CreationException expected) { assertContains(expected.getMessage(), "more than one annotation annotated with @BindingAnnotation:", "Named", "Blue", "at " + getClass().getName(), ".provideString(ProviderMethodsTest.java:"); } }
public void testTypeNotBoundByDefault() { Module module = new AbstractModule() { @Override protected void configure() { OptionalBinder.newOptionalBinder(binder(), String.class); requireBinding(new Key<Optional<String>>() {}); // the above specifies this. requireBinding(String.class); // but it doesn't specify this. binder().requireExplicitBindings(); // need to do this, otherwise String will JIT if (HAS_JAVA_OPTIONAL) { requireBinding(Key.get(javaOptionalOfString)); } } }; try { Guice.createInjector(module); fail(); } catch (CreationException ce) { assertContains( ce.getMessage(), "1) Explicit bindings are required and java.lang.String is not explicitly bound."); assertEquals(1, ce.getErrorMessages().size()); } }
public void testImplicitForwardingAssistedBindingFailsWithInterface() { try { Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Car.class).to(Golf.class); install(new FactoryModuleBuilder().build(ColoredCarFactory.class)); } }); fail(); } catch (CreationException ce) { assertContains( ce.getMessage(), "1) " + Car.class.getName() + " is an interface, not a concrete class.", "Unable to create AssistedInject factory.", "while locating " + Car.class.getName(), "at " + ColoredCarFactory.class.getName() + ".create("); assertEquals(1, ce.getErrorMessages().size()); } }
public void testOneMethodThatIsntGet() { try { Guice.createInjector(new AbstractModule() { protected void configure() { install(ThrowingProviderBinder.forModule(this)); } @SuppressWarnings("unused") @CheckedProvides(OneNoneGetMethod.class) String foo() { return null; } }); fail(); } catch(CreationException ce) { assertEquals(OneNoneGetMethod.class.getName() + " may not declare any new methods, but declared " + Classes.toString(OneNoneGetMethod.class.getDeclaredMethods()[0]), Iterables.getOnlyElement(ce.getErrorMessages()).getMessage()); } }
public void testIncorrectPredefinedType_Provides() { try { Guice.createInjector(new AbstractModule() { @Override protected void configure() { install(ThrowingProviderBinder.forModule(this)); } @SuppressWarnings("unused") @CheckedProvides(StringRemoteProvider.class) Integer foo() { return null; } }); fail(); } catch(CreationException ce) { assertEquals(StringRemoteProvider.class.getName() + " expects the value type to be java.lang.String, but it was java.lang.Integer", Iterables.getOnlyElement(ce.getErrorMessages()).getMessage()); } }
public void testOverrideProviderMethod_erasureBasedOverrides() { class SubClassModule extends GenericSuperModule<Integer> { @Override String provide(Integer thing) { return thing.toString(); } @Override protected void configure() { bind(Integer.class).toInstance(3); } } try { Guice.createInjector(new SubClassModule()); fail(); } catch (CreationException e) { assertContains( e.getMessage(), "Overriding @Provides methods is not allowed.", "@Provides method: " + GenericSuperModule.class.getName() + ".provide()", "overridden by: " + SubClassModule.class.getName() + ".provide()"); } }
public void testWrongThrowingProviderType() { try { Guice.createInjector( new AbstractModule() { @Override protected void configure() { install(ThrowingProviderBinder.forModule(this)); } @SuppressWarnings("unused") @CheckedProvides(WrongThrowingProviderType.class) String foo() { return null; } }); fail(); } catch (CreationException ce) { assertEquals( WrongThrowingProviderType.class.getName() + " does not properly extend CheckedProvider, the first type parameter of CheckedProvider " + "(java.lang.String) is not a generic type", Iterables.getOnlyElement(ce.getErrorMessages()).getMessage()); } }
@Test public void testConflictingDefaultPriorities() { thrown.expect(CreationException.class); thrown.expectMessage(containsString("2 errors")); thrown.expectMessage(containsString("1) Duplicate ListBinder<java.lang.String> with default priority")); thrown.expectMessage(containsString("2) Duplicate ListBinder<java.lang.String> with default priority")); thrown.expectMessage(containsString("at com.tavianator.sangria.listbinder.ListBinderTest")); Guice.createInjector(new AbstractModule() { @Override protected void configure() { ListBinder.build(binder(), String.class) .withDefaultPriority(); } }, new AbstractModule() { @Override protected void configure() { ListBinder.build(binder(), String.class) .withDefaultPriority(); } }); }
@Test public void testConflictingExplicitPriorities() { thrown.expect(CreationException.class); thrown.expectMessage(containsString("2 errors")); thrown.expectMessage(containsString("1) Duplicate ListBinder<java.lang.String> with priority [1]")); thrown.expectMessage(containsString("2) Duplicate ListBinder<java.lang.String> with priority [1]")); thrown.expectMessage(containsString("at com.tavianator.sangria.listbinder.ListBinderTest")); Guice.createInjector(new AbstractModule() { @Override protected void configure() { ListBinder.build(binder(), String.class) .withPriority(1); } }, new AbstractModule() { @Override protected void configure() { ListBinder.build(binder(), String.class) .withPriority(1); } }); }
@Test public void testConflictingDefaultAndExplicitPriorities() { thrown.expect(CreationException.class); thrown.expectMessage(containsString("2 errors")); thrown.expectMessage(containsString(") ListBinder<java.lang.String> with default priority conflicts with ListBinder with explicit priority")); thrown.expectMessage(containsString(") ListBinder<java.lang.String> with priority [1] conflicts with ListBinder with default priority")); thrown.expectMessage(containsString("at com.tavianator.sangria.listbinder.ListBinderTest")); Guice.createInjector(new AbstractModule() { @Override protected void configure() { ListBinder.build(binder(), String.class) .withDefaultPriority(); } }, new AbstractModule() { @Override protected void configure() { ListBinder.build(binder(), String.class) .withPriority(1); } }); }
public void testExplicitForwardingAssistedBindingFailsWithInterface() { try { Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Volkswagen.class).to(Golf.class); install(new FactoryModuleBuilder() .implement(Car.class, Volkswagen.class) .build(ColoredCarFactory.class)); } }); fail(); } catch (CreationException ce) { assertContains( ce.getMessage(), "1) " + Volkswagen.class.getName() + " is an interface, not a concrete class.", "Unable to create AssistedInject factory.", "while locating " + Volkswagen.class.getName(), "while locating " + Car.class.getName(), "at " + ColoredCarFactory.class.getName() + ".create("); assertEquals(1, ce.getErrorMessages().size()); } }
public void testBindingToSubSubInterface_Provides() throws Exception { try { Guice.createInjector(new AbstractModule() { @Override protected void configure() { install(ThrowingProviderBinder.forModule(this)); } @SuppressWarnings("unused") @CheckedProvides(SubRemoteProvider.class) Foo foo() { return null; } }); fail(); } catch (CreationException expected) { assertEquals(SubRemoteProvider.class.getName() + " must extend CheckedProvider (and only CheckedProvider)", Iterables.getOnlyElement(expected.getErrorMessages()).getMessage()); } }
public void testDifferentBindingsFail_actual() { Module module = new AbstractModule() { @Override protected void configure() { OptionalBinder.newOptionalBinder(binder(), String.class).setBinding().toInstance("a"); OptionalBinder.newOptionalBinder(binder(), String.class).setBinding().toInstance("b"); } }; try { Guice.createInjector(module); fail(); } catch (CreationException ce) { assertEquals(ce.getMessage(), 1, ce.getErrorMessages().size()); assertContains(ce.getMessage(), "1) OptionalBinder for java.lang.String called with different setBinding values, " + "from bindings:", "at " + module.getClass().getName() + ".configure(", "at " + module.getClass().getName() + ".configure(", "at " + MapBinder.RealMapBinder.class.getName()); } }
public void testGenericErrorMessageMakesSense() { try { Guice.createInjector(new AbstractModule() { @Override protected void configure() { install(new FactoryModuleBuilder().build(Key.get(Foo.Factory.class))); } }); fail(); } catch(CreationException ce ) { // Assert not only that it's the correct message, but also that it's the *only* message. Collection<Message> messages = ce.getErrorMessages(); assertEquals( Foo.Factory.class.getName() + " cannot be used as a key; It is not fully specified.", Iterables.getOnlyElement(messages).getMessage()); } }
public void testMapKeyMissingValueMethod() { Module m = new AbstractModule() { @ProvidesIntoMap @MissingValueMethod String provideFoo() { return "foo"; } }; try { Guice.createInjector(MultibindingsScanner.asModule(), m); fail(); } catch (CreationException ce) { assertEquals(1, ce.getErrorMessages().size()); assertContains( ce.getMessage(), "No 'value' method in MapKey with unwrapValue=true: " + MissingValueMethod.class.getName()); } }
public void testAssistedInjectConstructorAndAssistedFactoryParameterMustNotMix() { try { Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Double.class).toInstance(5.0d); bind(AssistedParamsFactory.class) .toProvider(FactoryProvider.newFactory(AssistedParamsFactory.class, Mustang.class)); } }); fail(); } catch (CreationException expected) { assertContains(expected.getMessage(), "Factory method " + AssistedParamsFactory.class.getName() + ".create() has an @Assisted parameter, which " + "is incompatible with the deprecated @AssistedInject annotation."); } }
public void testIncompatibleBindingType() { final Integer testInt = 1024; Object instance = new Object() { @Bind(to = String.class) private Integer anInt = testInt; }; BoundFieldModule module = BoundFieldModule.of(instance); try { Guice.createInjector(module); fail(); } catch (CreationException e) { assertContains(e.getMessage(), "Requested binding type \"java.lang.String\" is not assignable from field binding type " + "\"java.lang.Integer\""); } }
public void testArrayKeys_unwrapValuesTrue() { Module m = new AbstractModule() { @ProvidesIntoMap @ArrayUnwrappedKey({1, 2}) String provideFoo() { return "foo"; } }; try { Guice.createInjector(MultibindingsScanner.asModule(), m); fail(); } catch (CreationException ce) { assertEquals(1, ce.getErrorMessages().size()); assertContains( ce.getMessage(), "Array types are not allowed in a MapKey with unwrapValue=true: " + ArrayUnwrappedKey.class.getName(), "at " + m.getClass().getName() + ".provideFoo("); } }
public void testMoreTypeParameters() { try { Guice.createInjector(new AbstractModule() { @Override protected void configure() { install(ThrowingProviderBinder.forModule(this)); } @SuppressWarnings("unused") @CheckedProvides(TooManyTypeParameters.class) String foo() { return null; } }); fail(); } catch(CreationException ce) { assertEquals(TooManyTypeParameters.class.getName() + " has more than one generic type parameter: [T, P]", Iterables.getOnlyElement(ce.getErrorMessages()).getMessage()); } }
public void testFailureOnMultipleBindingAnnotations() { final Integer testInt = 1024; Object instance = new Object() { @Bind @Named("a") @SomeBindingAnnotation private Integer anInt = testInt; }; BoundFieldModule module = BoundFieldModule.of(instance); try { Guice.createInjector(module); fail(); } catch (CreationException e) { assertContains(e.getMessage(), "More than one annotation is specified for this binding."); } }
public void testBindingNonNullableNullField() { Object instance = new Object() { @Bind private Integer anInt = null; }; BoundFieldModule module = BoundFieldModule.of(instance); try { Guice.createInjector(module); fail(); } catch (CreationException e) { assertContains( e.getMessage(), "Binding to null values is only allowed for fields that are annotated @Nullable."); } }
public void testBindingNullProvider() { Object instance = new Object() { @Bind private Provider<Integer> anIntProvider = null; }; BoundFieldModule module = BoundFieldModule.of(instance); try { Guice.createInjector(module); fail(); } catch (CreationException e) { assertContains( e.getMessage(), "Binding to null is not allowed. Use Providers.of(null) if this is your intended " + "behavior."); } }
public void testBindingNullableNullProvider() { Object instance = new Object() { @Bind @Nullable private Provider<Integer> anIntProvider = null; }; BoundFieldModule module = BoundFieldModule.of(instance); try { Guice.createInjector(module); fail(); } catch (CreationException e) { assertContains( e.getMessage(), "Binding to null is not allowed. Use Providers.of(null) if this is your intended " + "behavior."); } }
public void testRawProviderCannotBeBound() { final Integer testValue = 1024; Object instance = new Object() { @Bind private Provider anIntProvider = new Provider() { @Override public Object get() { return testValue; } }; }; BoundFieldModule module = BoundFieldModule.of(instance); try { Guice.createInjector(module); fail(); } catch (CreationException e) { assertContains( e.getMessage(), "Non parameterized Provider fields must have an " + "explicit binding class via @Bind(to = Foo.class)"); } }
public void testOverridesTwiceFails() { Module original = newModule("A"); Module replacements = new OuterReplacementsModule(); Module module = Modules.override(original).with(replacements); try { createInjector(module); fail(); } catch (CreationException expected) { assertContains(expected.getMessage(), "A binding to java.lang.String was already configured at " + InnerReplacementsModule.class.getName(), asModuleChain(Modules.OverrideModule.class, OuterReplacementsModule.class, InnerReplacementsModule.class), "at " + InnerReplacementsModule.class.getName(), asModuleChain(Modules.OverrideModule.class, OuterReplacementsModule.class, InnerReplacementsModule.class)); } }
public void testProvidesIntoSetWithMapKey() { Module m = new AbstractModule() { @ProvidesIntoSet @TestEnumKey(TestEnum.A) String provideFoo() { return "foo"; } }; try { Guice.createInjector(MultibindingsScanner.asModule(), m); fail(); } catch (CreationException ce) { assertEquals(1, ce.getErrorMessages().size()); assertContains( ce.getMessage(), "Found a MapKey annotation on non map binding at " + m.getClass().getName() + ".provideFoo"); } }