KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > inject > BoundProviderTest


1 /**
2  * Copyright (C) 2006 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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  */

16
17 package com.google.inject;
18
19 import junit.framework.TestCase;
20
21 /**
22  * @author crazybob@google.com (Bob Lee)
23  */

24 public class BoundProviderTest extends TestCase {
25
26   public void testFooProvider() throws CreationException {
27     BinderImpl cb = new BinderImpl();
28     cb.bind(Foo.class).toProvider(FooProvider.class);
29     Injector c = cb.createInjector();
30
31     Foo a = c.getInstance(Foo.class);
32     Foo b = c.getInstance(Foo.class);
33
34     assertEquals(0, a.i);
35     assertEquals(0, b.i);
36     assertNotNull(a.bar);
37     assertNotNull(b.bar);
38     assertNotSame(a.bar, b.bar);
39   }
40
41   public void testSingletonFooProvider() throws CreationException {
42     BinderImpl cb = new BinderImpl();
43     cb.bind(Foo.class).toProvider(SingletonFooProvider.class);
44     Injector c = cb.createInjector();
45
46     Foo a = c.getInstance(Foo.class);
47     Foo b = c.getInstance(Foo.class);
48
49     assertEquals(0, a.i);
50     assertEquals(1, b.i);
51     assertNotNull(a.bar);
52     assertNotNull(b.bar);
53     assertSame(a.bar, b.bar);
54   }
55
56   static class Bar {}
57
58   static class Foo {
59     final Bar bar;
60     final int i;
61
62     Foo(Bar bar, int i) {
63       this.bar = bar;
64       this.i = i;
65     }
66   }
67
68   static class FooProvider implements Provider<Foo> {
69
70     final Bar bar;
71     int count = 0;
72
73     @Inject
74     public FooProvider(Bar bar) {
75       this.bar = bar;
76     }
77
78     public Foo get() {
79       return new Foo(this.bar, count++);
80     }
81   }
82
83   @Singleton
84   static class SingletonFooProvider implements Provider<Foo> {
85
86     final Bar bar;
87     int count = 0;
88
89     @Inject
90     public SingletonFooProvider(Bar bar) {
91       this.bar = bar;
92     }
93
94     public Foo get() {
95       return new Foo(this.bar, count++);
96     }
97   }
98 }
99
Popular Tags