@Test public void testSimpleInjection() throws Exception { //GIVEN Scope scope = new ScopeImpl(""); FooWithLazy fooWithLazy = new FooWithLazy(); //WHEN Toothpick.inject(fooWithLazy, scope); //THEN assertThat(fooWithLazy.bar, notNullValue()); assertThat(fooWithLazy.bar, isA(Lazy.class)); Bar bar1 = fooWithLazy.bar.get(); assertThat(bar1, isA(Bar.class)); Bar bar2 = fooWithLazy.bar.get(); assertThat(bar2, isA(Bar.class)); assertThat(bar2, sameInstance(bar1)); }
@Test(expected = IllegalStateException.class) public void lazyGet_shouldFail_whenScopeIsClosed_andThereAreNoDependencies() { //GIVEN ScopeImpl scope = new ScopeImpl(""); Lazy<Bar> lazy = scope.getLazy(Bar.class); //WHEN scope.close(); lazy.get(); //THEN }
@Test(expected = IllegalStateException.class) public void testLazyAfterClosingScope() throws Exception { //GIVEN String scopeName = ""; FooWithLazy fooWithLazy = new FooWithLazy(); //WHEN Toothpick.inject(fooWithLazy, Toothpick.openScope(scopeName)); Toothpick.closeScope(scopeName); System.gc(); //THEN fooWithLazy.bar.get(); // should crash } }
@Test(expected = IllegalStateException.class) public void lazyGet_shouldFail_whenScopeIsClosed() { //GIVEN ScopeImpl scope = new ScopeImpl(""); Lazy<Foo> lazy = scope.getLazy(Foo.class); //WHEN scope.close(); lazy.get(); //THEN }
@Test public void testNamedInjection() throws Exception { //GIVEN Scope scope = new ScopeImpl(""); scope.installModules(new Module() { { bind(Bar.class).withName("foo").to(Bar.class); } }); FooWithNamedLazy fooWithLazy = new FooWithNamedLazy(); //WHEN Toothpick.inject(fooWithLazy, scope); //THEN assertThat(fooWithLazy.bar, notNullValue()); assertThat(fooWithLazy.bar, isA(Lazy.class)); Bar bar1 = fooWithLazy.bar.get(); assertThat(bar1, isA(Bar.class)); Bar bar2 = fooWithLazy.bar.get(); assertThat(bar2, isA(Bar.class)); assertThat(bar2, sameInstance(bar1)); }