01: /**
02: * Copyright (C) 2006 Google Inc.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */package com.google.inject;
16:
17: import junit.framework.TestCase;
18:
19: /**
20: * @author crazybob@google.com (Bob Lee)
21: */
22: public class BoundProviderTest extends TestCase {
23:
24: public void testFooProvider() throws CreationException {
25: BinderImpl cb = new BinderImpl();
26: cb.bind(Foo.class).toProvider(FooProvider.class);
27: Injector c = cb.createInjector();
28:
29: Foo a = c.getInstance(Foo.class);
30: Foo b = c.getInstance(Foo.class);
31:
32: assertEquals(0, a.i);
33: assertEquals(0, b.i);
34: assertNotNull(a.bar);
35: assertNotNull(b.bar);
36: assertNotSame(a.bar, b.bar);
37: }
38:
39: public void testSingletonFooProvider() throws CreationException {
40: BinderImpl cb = new BinderImpl();
41: cb.bind(Foo.class).toProvider(SingletonFooProvider.class);
42: Injector c = cb.createInjector();
43:
44: Foo a = c.getInstance(Foo.class);
45: Foo b = c.getInstance(Foo.class);
46:
47: assertEquals(0, a.i);
48: assertEquals(1, b.i);
49: assertNotNull(a.bar);
50: assertNotNull(b.bar);
51: assertSame(a.bar, b.bar);
52: }
53:
54: static class Bar {
55: }
56:
57: static class Foo {
58: final Bar bar;
59: final int i;
60:
61: Foo(Bar bar, int i) {
62: this .bar = bar;
63: this .i = i;
64: }
65: }
66:
67: static class FooProvider implements Provider<Foo> {
68:
69: final Bar bar;
70: int count = 0;
71:
72: @Inject
73: public FooProvider(Bar bar) {
74: this .bar = bar;
75: }
76:
77: public Foo get() {
78: return new Foo(this .bar, count++);
79: }
80: }
81:
82: @Singleton
83: static class SingletonFooProvider implements Provider<Foo> {
84:
85: final Bar bar;
86: int count = 0;
87:
88: @Inject
89: public SingletonFooProvider(Bar bar) {
90: this .bar = bar;
91: }
92:
93: public Foo get() {
94: return new Foo(this.bar, count++);
95: }
96: }
97: }
|