File: BinderTest.java

package info (click to toggle)
guice 5.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,692 kB
  • sloc: java: 72,879; xml: 1,431; sh: 58; jsp: 12; makefile: 5
file content (692 lines) | stat: -rw-r--r-- 22,861 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
/*
 * Copyright (C) 2007 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.inject;

import static com.google.inject.Asserts.assertContains;
import static com.google.inject.Asserts.assertNotSerializable;
import static com.google.inject.Asserts.getDeclaringSourcePart;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.inject.internal.Annotations;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
import com.google.inject.spi.Message;
import com.google.inject.util.Providers;
import java.io.IOException;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import junit.framework.TestCase;

/** @author crazybob@google.com (Bob Lee) */
public class BinderTest extends TestCase {

  private final Logger loggerToWatch = Logger.getLogger(Guice.class.getName());

  private final List<LogRecord> logRecords = Lists.newArrayList();
  private final Handler fakeHandler =
      new Handler() {
        @Override
        public void publish(LogRecord logRecord) {
          logRecords.add(logRecord);
        }

        @Override
        public void flush() {}

        @Override
        public void close() throws SecurityException {}
      };

  Provider<Foo> fooProvider;

  @Override
  protected void setUp() throws Exception {
    super.setUp();
    loggerToWatch.addHandler(fakeHandler);
  }

  @Override
  protected void tearDown() throws Exception {
    loggerToWatch.removeHandler(fakeHandler);
    super.tearDown();
  }

  public void testProviderFromBinder() {
    Guice.createInjector(
        new Module() {
          @Override
          public void configure(Binder binder) {
            fooProvider = binder.getProvider(Foo.class);

            try {
              fooProvider.get();
              fail();
            } catch (IllegalStateException e) {
              /* expected */
            }
          }
        });

    assertNotNull(fooProvider.get());
  }

  static class Foo {}

  public void testMissingBindings() {
    try {
      Guice.createInjector(
          // We put each binding in a separate module so the order of the error messages doesn't
          // depend on line numbers
          new AbstractModule() {
            @Override
            public void configure() {
              getProvider(Runnable.class);
            }
          },
          new AbstractModule() {
            @Override
            public void configure() {
              bind(Comparator.class);
            }
          },
          new AbstractModule() {
            @Override
            public void configure() {
              requireBinding(Key.get(new TypeLiteral<Callable<String>>() {}));
            }
          },
          new AbstractModule() {
            @Override
            public void configure() {
              bind(Date.class).annotatedWith(Names.named("date"));
            }
          });
      fail("Expected CreationException");
    } catch (CreationException e) {
      assertEquals(4, e.getErrorMessages().size());
      String segment1 = "No implementation for Runnable was bound.";
      String segment2 = "No implementation for Comparator was bound.";
      String segment3 = "No implementation for Callable<String> was bound.";
      String segment4 =
          String.format(
              "No implementation for Date annotated with @Named(%s) was bound.",
              Annotations.memberValueString("value", "date"));
      String sourceFileName = getDeclaringSourcePart(getClass());
      assertContains(
          e.getMessage(),
          segment1,
          sourceFileName,
          segment2,
          sourceFileName,
          segment3,
          sourceFileName,
          segment4,
          sourceFileName);
    }
  }

  public void testMissingDependency() {
    try {
      Guice.createInjector(
          new AbstractModule() {
            @Override
            public void configure() {
              bind(NeedsRunnable.class);
            }
          });
      fail("Expected CreationException");
    } catch (CreationException e) {
      assertEquals(1, e.getErrorMessages().size());
      assertContains(
          e.getMessage(),
          "No implementation for Runnable was bound.",
          ".runnable",
          "for field runnable",
          "at BinderTest$7.configure");
    }
  }

  static class NeedsRunnable {
    @Inject Runnable runnable;
  }

  public void testDanglingConstantBinding() {
    try {
      Guice.createInjector(
          new AbstractModule() {
            @Override
            public void configure() {
              bindConstant();
            }
          });
      fail();
    } catch (CreationException expected) {
      assertContains(
          expected.getMessage(),
          "Missing constant value. Please call to(...).",
          "at BinderTest$8.configure");
    }
  }

  public void testRecursiveBinding() {
    try {
      Guice.createInjector(
          new AbstractModule() {
            @Override
            public void configure() {
              bind(Runnable.class).to(Runnable.class);
            }
          });
      fail();
    } catch (CreationException expected) {
      assertContains(
          expected.getMessage(), "Binding points to itself.", "at BinderTest$9.configure");
    }
  }

  public void testBindingNullConstant() {
    try {
      Guice.createInjector(
          new AbstractModule() {
            @Override
            public void configure() {
              String none = null;
              bindConstant().annotatedWith(Names.named("nullOne")).to(none);
              bind(String.class).annotatedWith(Names.named("nullTwo")).toInstance(none);
            }
          });
      fail();
    } catch (CreationException expected) {
      assertContains(
          expected.getMessage(),
          "1) Binding to null instances is not allowed. Use toProvider(Providers.of(null))",
          "2) Binding to null instances is not allowed. Use toProvider(Providers.of(null))");
    }
  }

  public void testToStringOnBinderApi() {
    try {
      Guice.createInjector(
          new AbstractModule() {
            @Override
            public void configure() {
              assertEquals("Binder", binder().toString());
              assertEquals("Provider<java.lang.Integer>", getProvider(Integer.class).toString());
              assertEquals(
                  "Provider<java.util.List<java.lang.String>>",
                  getProvider(Key.get(new TypeLiteral<List<String>>() {})).toString());

              assertEquals("BindingBuilder<java.lang.Integer>", bind(Integer.class).toString());
              assertEquals(
                  "BindingBuilder<java.lang.Integer>",
                  bind(Integer.class).annotatedWith(Names.named("a")).toString());
              assertEquals("ConstantBindingBuilder", bindConstant().toString());
              assertEquals(
                  "ConstantBindingBuilder",
                  bindConstant().annotatedWith(Names.named("b")).toString());
              assertEquals(
                  "AnnotatedElementBuilder",
                  binder().newPrivateBinder().expose(Integer.class).toString());
            }
          });
      fail();
    } catch (CreationException ignored) {
    }
  }

  public void testNothingIsSerializableInBinderApi() {
    try {
      Guice.createInjector(
          new AbstractModule() {
            @Override
            public void configure() {
              try {
                assertNotSerializable(binder());
                assertNotSerializable(getProvider(Integer.class));
                assertNotSerializable(getProvider(Key.get(new TypeLiteral<List<String>>() {})));
                assertNotSerializable(bind(Integer.class));
                assertNotSerializable(bind(Integer.class).annotatedWith(Names.named("a")));
                assertNotSerializable(bindConstant());
                assertNotSerializable(bindConstant().annotatedWith(Names.named("b")));
              } catch (IOException e) {
                fail(e.getMessage());
              }
            }
          });
      fail();
    } catch (CreationException ignored) {
    }
  }

  /**
   * Although {@code String[].class} isn't equal to {@code new GenericArrayTypeImpl(String.class)},
   * Guice should treat these two types interchangeably.
   */
  public void testArrayTypeCanonicalization() {
    final String[] strings = new String[] {"A"};
    final Integer[] integers = new Integer[] {1};

    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(String[].class).toInstance(strings);
                bind(new TypeLiteral<Integer[]>() {}).toInstance(integers);
              }
            });

    assertSame(integers, injector.getInstance(Key.get(new TypeLiteral<Integer[]>() {})));
    assertSame(integers, injector.getInstance(new Key<Integer[]>() {}));
    assertSame(integers, injector.getInstance(Integer[].class));
    assertSame(strings, injector.getInstance(Key.get(new TypeLiteral<String[]>() {})));
    assertSame(strings, injector.getInstance(new Key<String[]>() {}));
    assertSame(strings, injector.getInstance(String[].class));

    try {
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              bind(String[].class).toInstance(new String[] {"A"});
              bind(new TypeLiteral<String[]>() {}).toInstance(new String[] {"B"});
            }
          });
      fail();
    } catch (CreationException expected) {
      assertContains(
          expected.getMessage(),
          "String[] was bound multiple times.",
          "1  : BinderTest$18.configure",
          "2  : BinderTest$18.configure");
      assertContains(expected.getMessage(), "1 error");
    }

    // passes because duplicates are ignored
    injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(String[].class).toInstance(strings);
                bind(new TypeLiteral<String[]>() {}).toInstance(strings);
              }
            });
    assertSame(strings, injector.getInstance(Key.get(new TypeLiteral<String[]>() {})));
    assertSame(strings, injector.getInstance(new Key<String[]>() {}));
    assertSame(strings, injector.getInstance(String[].class));
  }

  static class ParentModule extends AbstractModule {
    @Override
    protected void configure() {
      install(new FooModule());
      install(new BarModule());
    }
  }

  static class FooModule extends AbstractModule {
    @Override
    protected void configure() {
      install(new ConstantModule("foo"));
    }
  }

  static class BarModule extends AbstractModule {
    @Override
    protected void configure() {
      install(new ConstantModule("bar"));
    }
  }

  static class ConstantModule extends AbstractModule {
    private final String constant;

    ConstantModule(String constant) {
      this.constant = constant;
    }

    @Override
    protected void configure() {
      bind(String.class).toInstance(constant);
    }
  }

  /** Binding something to two different things should give an error. */
  public void testSettingBindingTwice() {
    try {
      Guice.createInjector(new ParentModule());
      fail();
    } catch (CreationException expected) {
      assertContains(
          expected.getMessage(),
          "String was bound multiple times.",
          " BinderTest$ParentModule -> BinderTest$FooModule -> BinderTest$ConstantModule",
          " BinderTest$ParentModule -> BinderTest$BarModule -> BinderTest$ConstantModule");
      assertContains(expected.getMessage(), "1 error");
    }
  }

  /** Binding an @ImplementedBy thing to something else should also fail. */
  public void testSettingAtImplementedByTwice() {
    try {
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              bind(HasImplementedBy1.class);
              bind(HasImplementedBy1.class).toInstance(new HasImplementedBy1() {});
            }
          });
      fail();
    } catch (CreationException expected) {
      expected.printStackTrace();
      assertContains(
          expected.getMessage(),
          "BinderTest$HasImplementedBy1 was bound multiple times.",
          "1  : BinderTest$22.configure",
          "2  : BinderTest$HasImplementedBy1.class");
      assertContains(expected.getMessage(), "1 error");
    }
  }

  /** See issue 614, Problem One https://github.com/google/guice/issues/614 */
  public void testJitDependencyDoesntBlockOtherExplicitBindings() {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(HasImplementedByThatNeedsAnotherImplementedBy.class);
                bind(HasImplementedBy1.class).toInstance(new HasImplementedBy1() {});
              }
            });
    injector.getAllBindings(); // just validate it doesn't throw.
    // Also validate that we're using the explicit (and not @ImplementedBy) implementation
    assertFalse(
        injector.getInstance(HasImplementedBy1.class) instanceof ImplementsHasImplementedBy1);
  }

  /** See issue 614, Problem Two https://github.com/google/guice/issues/id=614 */
  public void testJitDependencyCanUseExplicitDependencies() {
    Guice.createInjector(
        new AbstractModule() {
          @Override
          protected void configure() {
            bind(HasImplementedByThatWantsExplicit.class);
            bind(JustAnInterface.class).toInstance(new JustAnInterface() {});
          }
        });
  }

  /**
   * Untargetted bindings should follow @ImplementedBy and @ProvidedBy annotations if they exist.
   * Otherwise the class should be constructed directly.
   */
  public void testUntargettedBinding() {
    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(HasProvidedBy1.class);
                bind(HasImplementedBy1.class);
                bind(HasProvidedBy2.class);
                bind(HasImplementedBy2.class);
                bind(JustAClass.class);
              }
            });

    assertNotNull(injector.getInstance(HasProvidedBy1.class));
    assertNotNull(injector.getInstance(HasImplementedBy1.class));
    assertNotSame(HasProvidedBy2.class, injector.getInstance(HasProvidedBy2.class).getClass());
    assertSame(
        ExtendsHasImplementedBy2.class, injector.getInstance(HasImplementedBy2.class).getClass());
    assertSame(JustAClass.class, injector.getInstance(JustAClass.class).getClass());
  }

  public void testPartialInjectorGetInstance() {
    Injector injector = Guice.createInjector();
    try {
      injector.getInstance(MissingParameter.class);
      fail();
    } catch (ConfigurationException expected) {
      assertContains(
          expected.getMessage(),
          "No injectable constructor for type BinderTest$NoInjectConstructor.",
          "at BinderTest$MissingParameter.<init>",
          "for 1st parameter noInjectConstructor");
    }
  }

  public void testUserReportedError() {
    final Message message = new Message(getClass(), "Whoops!");
    try {
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              addError(message);
            }
          });
      fail();
    } catch (CreationException expected) {
      assertSame(message, Iterables.getOnlyElement(expected.getErrorMessages()));
    }
  }

  public void testUserReportedErrorsAreAlsoLogged() {
    try {
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              addError(new Message("Whoops!", new IllegalArgumentException()));
            }
          });
      fail();
    } catch (CreationException expected) {
    }

    LogRecord logRecord = Iterables.getOnlyElement(this.logRecords);
    assertContains(
        logRecord.getMessage(),
        "An exception was caught and reported. Message: java.lang.IllegalArgumentException");
  }

  public void testBindingToProvider() {
    try {
      Guice.createInjector(
          new AbstractModule() {
            @Override
            protected void configure() {
              bind(new TypeLiteral<Provider<String>>() {}).toInstance(Providers.of("A"));
            }
          });
      fail();
    } catch (CreationException expected) {
      assertContains(
          expected.getMessage(),
          "Binding to Provider is not allowed.",
          "at BinderTest$28.configure");
    }
  }

  static class OuterCoreModule extends AbstractModule {
    @Override
    protected void configure() {
      install(new InnerCoreModule());
    }
  }

  static class InnerCoreModule extends AbstractModule {
    final Named red = Names.named("red");

    @Override
    protected void configure() {
      bind(AbstractModule.class).annotatedWith(red).toProvider(Providers.of(null));
      bind(Binder.class).annotatedWith(red).toProvider(Providers.of(null));
      bind(Binding.class).annotatedWith(red).toProvider(Providers.of(null));
      bind(Injector.class).annotatedWith(red).toProvider(Providers.of(null));
      bind(Key.class).annotatedWith(red).toProvider(Providers.of(null));
      bind(Module.class).annotatedWith(red).toProvider(Providers.of(null));
      bind(Provider.class).annotatedWith(red).toProvider(Providers.of(null));
      bind(Scope.class).annotatedWith(red).toProvider(Providers.of(null));
      bind(Stage.class).annotatedWith(red).toProvider(Providers.of(null));
      bind(TypeLiteral.class).annotatedWith(red).toProvider(Providers.of(null));
      bind(new TypeLiteral<Key<String>>() {}).toProvider(Providers.of(null));
    }
  }

  public void testCannotBindToGuiceTypes() {
    try {
      Guice.createInjector(new OuterCoreModule());
      fail();
    } catch (CreationException expected) {
      String methodLocation = "at BinderTest$InnerCoreModule.configure";
      String moduleChain = "installed by: BinderTest$OuterCoreModule -> BinderTest$InnerCoreModule";
      assertContains(
          expected.getMessage(),
          "Binding to core guice framework type is not allowed: AbstractModule.",
          methodLocation,
          moduleChain,
          "Binding to core guice framework type is not allowed: Binder.",
          methodLocation,
          moduleChain,
          "Binding to core guice framework type is not allowed: Binding.",
          methodLocation,
          moduleChain,
          "Binding to core guice framework type is not allowed: Injector.",
          methodLocation,
          moduleChain,
          "Binding to core guice framework type is not allowed: Key.",
          methodLocation,
          moduleChain,
          "Binding to core guice framework type is not allowed: Module.",
          methodLocation,
          moduleChain,
          "Binding to Provider is not allowed.",
          methodLocation,
          moduleChain,
          "Binding to core guice framework type is not allowed: Scope.",
          methodLocation,
          moduleChain,
          "Binding to core guice framework type is not allowed: Stage.",
          methodLocation,
          moduleChain,
          "Binding to core guice framework type is not allowed: TypeLiteral.",
          methodLocation,
          moduleChain,
          "Binding to core guice framework type is not allowed: Key.",
          methodLocation,
          moduleChain);
    }
  }

  static class MissingParameter {
    @Inject
    MissingParameter(NoInjectConstructor noInjectConstructor) {}
  }

  static class NoInjectConstructor {
    private NoInjectConstructor() {}
  }

  @ProvidedBy(HasProvidedBy1Provider.class)
  interface HasProvidedBy1 {}

  static class HasProvidedBy1Provider implements Provider<HasProvidedBy1> {
    @Override
    public HasProvidedBy1 get() {
      return new HasProvidedBy1() {};
    }
  }

  @ImplementedBy(ImplementsHasImplementedBy1.class)
  interface HasImplementedBy1 {}

  static class ImplementsHasImplementedBy1 implements HasImplementedBy1 {}

  @ProvidedBy(HasProvidedBy2Provider.class)
  static class HasProvidedBy2 {}

  static class HasProvidedBy2Provider implements Provider<HasProvidedBy2> {
    @Override
    public HasProvidedBy2 get() {
      return new HasProvidedBy2() {};
    }
  }

  @ImplementedBy(ExtendsHasImplementedBy2.class)
  static class HasImplementedBy2 {}

  static class ExtendsHasImplementedBy2 extends HasImplementedBy2 {}

  static class JustAClass {}

  @ImplementedBy(ImplementsHasImplementedByThatNeedsAnotherImplementedBy.class)
  static interface HasImplementedByThatNeedsAnotherImplementedBy {}

  static class ImplementsHasImplementedByThatNeedsAnotherImplementedBy
      implements HasImplementedByThatNeedsAnotherImplementedBy {
    @Inject
    ImplementsHasImplementedByThatNeedsAnotherImplementedBy(HasImplementedBy1 h1n1) {}
  }

  @ImplementedBy(ImplementsHasImplementedByThatWantsExplicit.class)
  static interface HasImplementedByThatWantsExplicit {}

  static class ImplementsHasImplementedByThatWantsExplicit
      implements HasImplementedByThatWantsExplicit {
    @Inject
    ImplementsHasImplementedByThatWantsExplicit(JustAnInterface jai) {}
  }

  static interface JustAnInterface {}

  //  public void testBindInterfaceWithoutImplementation() {
  //    Guice.createInjector(new AbstractModule() {
  //      protected void configure() {
  //        bind(Runnable.class);
  //      }
  //    }).getInstance(Runnable.class);
  //  }

  enum Roshambo {
    ROCK,
    SCISSORS,
    PAPER
  }

  public void testInjectRawProvider() {
    try {
      Guice.createInjector().getInstance(Provider.class);
      fail();
    } catch (ConfigurationException expected) {
      Asserts.assertContains(
          expected.getMessage(),
          "Cannot inject a Provider that has no type parameter",
          "while locating Provider");
    }
  }
}