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.enterprise.context.RequestScoped;
22 import javax.inject.Inject;
23 import javax.naming.InitialContext;
25 import org.junit.After;
26 import org.junit.Before;
27 import org.junit.Test;
28 import org.wamblee.inject.Injector;
29 import org.wamblee.inject.InjectorFactory;
30 import org.wamblee.inject.InjectorFactoryBuilder;
31 import org.wamblee.inject.SimpleInjector;
32 import org.wamblee.test.jndi.StubInitialContextFactory;
34 public class SimpleInjectorTest extends BaseTestFixture {
36 private BeanManagerSetup setup;
39 public void setUp() throws Exception {
41 setup = new BeanManagerSetup();
43 StubInitialContextFactory.register();
44 InitialContext ctx = new InitialContext();
45 ctx.bind(BeanManagerLookup.BEAN_MANAGER_JNDI, setup.getBeanManager());
50 public void tearDown() throws Exception {
51 StubInitialContextFactory.unregister();
57 public void testGetSingleton() {
58 MyPojo pojo = new MyPojo();
59 SimpleInjector injector = new SimpleInjector(new CdiInjectorFactory(BeanManagerLookup.lookup()));
60 injector.inject(pojo);
62 MySingleton obj = pojo.getSingleton();
65 MyPojo pojo2 = new MyPojo();
66 injector.inject(pojo2);
68 // Objects will not be the same as they are contextual references to the
70 // assertSame(pojo2, pojo);
72 assertEquals(1, MySingleton.getInstances());
76 public void testGetSingletonCustomInjector() {
77 MyPojo pojo = new MyPojo();
78 InjectorFactory factory = mock(InjectorFactory.class);
79 SimpleInjector injector = new SimpleInjector(factory);
80 final MySingleton singleton = new MySingleton();
81 when(factory.create(MyPojo.class)).thenReturn(new Injector() {
83 public void inject(Object aComponent) {
84 MyPojo pojo2 = (MyPojo) aComponent;
85 pojo2.setSingleton(singleton);
89 injector.inject(pojo);
90 // verify the custom injector was called.
91 assertSame(singleton, pojo.getSingleton());
95 public static class Y {
98 public static class X {
105 public void testInjectStorage() throws Exception {
107 InjectorFactoryBuilder.setInjectorFactory(null);
108 InjectorFactoryBuilder.getInjector().inject(x);
112 public void testInjectStorage2() {
114 InjectorFactoryBuilder.setInjectorFactory(null);
115 InjectorFactoryBuilder.getInjector().inject(x);