(no commit message)
[utils] / support / cdi / src / test / java / org / wamblee / cdi / SimpleInjectorTest.java
1 /*
2  * Copyright 2005-2010 the original author or authors.
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 package org.wamblee.cdi;
17
18 import static junit.framework.Assert.*;
19 import static org.mockito.Mockito.*;
20
21 import javax.naming.InitialContext;
22
23 import org.junit.After;
24 import org.junit.Before;
25 import org.junit.Test;
26 import org.wamblee.support.jndi.StubInitialContextFactory;
27
28 public class SimpleInjectorTest {
29
30     private BeanManagerSetup setup;
31
32     @Before
33     public void setUp() throws Exception {
34         setup = new BeanManagerSetup();
35         setup.initialize();
36         StubInitialContextFactory.register();
37         InitialContext ctx = new InitialContext();
38         ctx.bind(BeanManagerLookup.BEAN_MANAGER_JNDI, setup.getBeanManager());
39         MySingleton.reset();
40     }
41
42     @After
43     public void tearDown() {
44         StubInitialContextFactory.unregister();
45         setup.shutdown();
46     }
47
48     @Test
49     public void testGetSingleton() {
50         MyPojo pojo = new MyPojo();
51         SimpleInjector injector = new SimpleInjector();
52         injector.inject(pojo);
53
54         MySingleton obj = pojo.getSingleton();
55         assertNotNull(obj);
56
57         MyPojo pojo2 = new MyPojo();
58         injector.inject(pojo2);
59
60         // Objects will not be the same as they are contextual references to the
61         // same object.
62         // assertSame(pojo2, pojo);
63
64         assertEquals(1, MySingleton.getInstances());
65     }
66
67     @Test
68     public void testGetSingletonCustomInjector() {
69         MyPojo pojo = new MyPojo();
70         InjectorFactory factory = mock(InjectorFactory.class);
71         SimpleInjector injector = new SimpleInjector(factory);
72         final MySingleton singleton = new MySingleton();
73         when(factory.create(MyPojo.class)).thenReturn(new Injector() {
74             @Override
75             public void inject(Object aComponent) {
76                 MyPojo pojo2 = (MyPojo) aComponent;
77                 pojo2.setSingleton(singleton); 
78             }
79         });
80         
81         injector.inject(pojo);
82         // verify the custom injector was called. 
83         assertSame(singleton, pojo.getSingleton());
84     }
85 }