(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     }
40
41     @After
42     public void tearDown() {
43         StubInitialContextFactory.unregister();
44         setup.shutdown();
45     }
46
47     @Test
48     public void testGetSingleton() {
49         MyPojo pojo = new MyPojo();
50         SimpleInjector injector = new SimpleInjector();
51         injector.inject(pojo);
52
53         MySingleton obj = pojo.getSingleton();
54         assertNotNull(obj);
55
56         MyPojo pojo2 = new MyPojo();
57         injector.inject(pojo2);
58
59         // Objects will not be the same as they are contextual references to the
60         // same object.
61         // assertSame(pojo2, pojo);
62
63         assertEquals(1, MySingleton.getInstances());
64     }
65
66     @Test
67     public void testGetSingletonCustomInjector() {
68         MyPojo pojo = new MyPojo();
69         InjectorFactory factory = mock(InjectorFactory.class);
70         SimpleInjector injector = new SimpleInjector(factory);
71         final MySingleton singleton = new MySingleton();
72         when(factory.create(MyPojo.class)).thenReturn(new Injector() {
73             @Override
74             public void inject(Object aComponent) {
75                 MyPojo pojo2 = (MyPojo) aComponent;
76                 pojo2.setSingleton(singleton); 
77             }
78         });
79         
80         injector.inject(pojo);
81         // verify the custom injector was called. 
82         assertSame(singleton, pojo.getSingleton());
83     }
84 }