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.support.jndi.StubInitialContextFactory;
28 public class SimpleInjectorTest {
30 private BeanManagerSetup setup;
33 public void setUp() throws Exception {
34 setup = new BeanManagerSetup();
36 StubInitialContextFactory.register();
37 InitialContext ctx = new InitialContext();
38 ctx.bind(BeanManagerLookup.BEAN_MANAGER_JNDI, setup.getBeanManager());
43 public void tearDown() {
44 StubInitialContextFactory.unregister();
49 public void testGetSingleton() {
50 MyPojo pojo = new MyPojo();
51 SimpleInjector injector = new SimpleInjector();
52 injector.inject(pojo);
54 MySingleton obj = pojo.getSingleton();
57 MyPojo pojo2 = new MyPojo();
58 injector.inject(pojo2);
60 // Objects will not be the same as they are contextual references to the
62 // assertSame(pojo2, pojo);
64 assertEquals(1, MySingleton.getInstances());
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() {
75 public void inject(Object aComponent) {
76 MyPojo pojo2 = (MyPojo) aComponent;
77 pojo2.setSingleton(singleton);
81 injector.inject(pojo);
82 // verify the custom injector was called.
83 assertSame(singleton, pojo.getSingleton());