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