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.InjectorBuilder;
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(
60 BeanManagerLookup.lookup()));
61 injector.inject(pojo);
63 MySingleton obj = pojo.getSingleton();
66 MyPojo pojo2 = new MyPojo();
67 injector.inject(pojo2);
69 // Objects will not be the same as they are contextual references to the
71 // assertSame(pojo2, pojo);
73 assertEquals(1, MySingleton.getInstances());
77 public void testGetSingletonCustomInjector() {
78 MyPojo pojo = new MyPojo();
79 InjectorFactory factory = mock(InjectorFactory.class);
80 SimpleInjector injector = new SimpleInjector(factory);
81 final MySingleton singleton = new MySingleton();
82 when(factory.create(MyPojo.class)).thenReturn(new Injector() {
84 public void inject(Object aComponent) {
85 MyPojo pojo2 = (MyPojo) aComponent;
86 pojo2.setSingleton(singleton);
90 injector.inject(pojo);
91 // verify the custom injector was called.
92 assertSame(singleton, pojo.getSingleton());
96 public static class Y {
100 public static class X {
107 public void testInjectStorage() throws Exception {
109 InjectorBuilder.setInjectorFactory(null);
110 InjectorBuilder.getInjector().inject(x);
114 public void testInjectStorage2() {
116 InjectorBuilder.setInjectorFactory(null);
117 InjectorBuilder.getInjector().inject(x);