2 * Copyright 2005-2010 the original author or authors.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.wamblee.cdi;
18 import static junit.framework.Assert.*;
19 import static org.mockito.Mockito.*;
21 import javax.naming.InitialContext;
23 import org.junit.After;
24 import org.junit.Before;
25 import org.junit.Test;
26 import org.wamblee.inject.Injector;
27 import org.wamblee.inject.InjectorFactory;
28 import org.wamblee.inject.SimpleInjector;
29 import org.wamblee.support.jndi.StubInitialContextFactory;
31 public class SimpleInjectorTest {
33 private BeanManagerSetup setup;
36 public void setUp() throws Exception {
37 setup = new BeanManagerSetup();
39 StubInitialContextFactory.register();
40 InitialContext ctx = new InitialContext();
41 ctx.bind(BeanManagerLookup.BEAN_MANAGER_JNDI, setup.getBeanManager());
46 public void tearDown() {
47 StubInitialContextFactory.unregister();
52 public void testGetSingleton() {
53 MyPojo pojo = new MyPojo();
54 SimpleInjector injector = new SimpleInjector(new CdiInjectorFactory());
55 injector.inject(pojo);
57 MySingleton obj = pojo.getSingleton();
60 MyPojo pojo2 = new MyPojo();
61 injector.inject(pojo2);
63 // Objects will not be the same as they are contextual references to the
65 // assertSame(pojo2, pojo);
67 assertEquals(1, MySingleton.getInstances());
71 public void testGetSingletonCustomInjector() {
72 MyPojo pojo = new MyPojo();
73 InjectorFactory factory = mock(InjectorFactory.class);
74 SimpleInjector injector = new SimpleInjector(factory);
75 final MySingleton singleton = new MySingleton();
76 when(factory.create(MyPojo.class)).thenReturn(new Injector() {
78 public void inject(Object aComponent) {
79 MyPojo pojo2 = (MyPojo) aComponent;
80 pojo2.setSingleton(singleton);
84 injector.inject(pojo);
85 // verify the custom injector was called.
86 assertSame(singleton, pojo.getSingleton());