1 package com.google.inject; 2 3 import static com.google.inject.Asserts.assertContains; 4 5 import com.google.inject.name.Names; 6 7 import junit.framework.TestCase; 8 9 import java.util.logging.Logger; 10 11 /** 12 * Test built-in injection of loggers. 13 * 14 * @author jessewilson 15 */ 16 public class LoggerInjectionTest extends TestCase { 17 18 @Inject Logger logger; 19 testLoggerWithMember()20 public void testLoggerWithMember() { 21 Injector injector = Guice.createInjector(); 22 injector.injectMembers(this); 23 assertEquals("com.google.inject.LoggerInjectionTest", logger.getName()); 24 } 25 testLoggerInConstructor()26 public void testLoggerInConstructor() { 27 Injector injector = Guice.createInjector(); 28 Foo foo = injector.getInstance(Foo.class); 29 assertEquals("com.google.inject.LoggerInjectionTest$Foo", foo.logger.getName()); 30 } 31 32 private static class Foo { 33 Logger logger; 34 @SuppressWarnings("unused") Foo(Logger logger)35 @Inject Foo(Logger logger) { 36 this.logger = logger; 37 } 38 } 39 testLoggerWithoutMember()40 public void testLoggerWithoutMember() { 41 Injector injector = Guice.createInjector(); 42 assertNull(injector.getInstance(Logger.class).getName()); 43 assertNull(injector.getProvider(Logger.class).get().getName()); 44 assertNull(injector.getBinding(Logger.class).getProvider().get().getName()); 45 assertEquals("Provider<Logger>", injector.getProvider(Logger.class).toString()); 46 } 47 testCanBindAnnotatedLogger()48 public void testCanBindAnnotatedLogger() { 49 Injector injector = Guice.createInjector(new AbstractModule() { 50 protected void configure() { 51 bind(Logger.class) 52 .annotatedWith(Names.named("anonymous")) 53 .toInstance(Logger.getAnonymousLogger()); 54 } 55 }); 56 57 assertNull(injector.getInstance(Key.get(Logger.class, Names.named("anonymous"))).getName()); 58 } 59 testCannotBindLogger()60 public void testCannotBindLogger() { 61 try { 62 Guice.createInjector(new AbstractModule() { 63 protected void configure() { 64 bind(Logger.class).toInstance(Logger.getAnonymousLogger()); 65 } 66 }); 67 fail(); 68 } catch (CreationException expected) { 69 assertContains(expected.getMessage(), 70 "A binding to java.util.logging.Logger was already configured"); 71 } 72 } 73 } 74