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.cdi.BeanManagerSetup;
33 import org.wamblee.test.jndi.StubInitialContextFactory;
35 public class SimpleInjectorTest extends BaseTestFixture {
37 private BeanManagerSetup setup;
40 public void setUp() throws Exception {
42 setup = new BeanManagerSetup();
44 StubInitialContextFactory.register();
45 InitialContext ctx = new InitialContext();
46 ctx.bind(BeanManagerLookup.BEAN_MANAGER_JNDI, setup.getBeanManager());
51 public void tearDown() throws Exception {
52 StubInitialContextFactory.unregister();
58 public void testGetSingleton() {
59 MyPojo pojo = new MyPojo();
60 SimpleInjector injector = new SimpleInjector(new CdiInjectorFactory(
61 BeanManagerLookup.lookup()));
62 injector.inject(pojo);
64 MySingleton obj = pojo.getSingleton();
67 MyPojo pojo2 = new MyPojo();
68 injector.inject(pojo2);
70 // Objects will not be the same as they are contextual references to the
72 // assertSame(pojo2, pojo);
74 assertEquals(1, MySingleton.getInstances());
78 public void testGetSingletonCustomInjector() {
79 MyPojo pojo = new MyPojo();
80 InjectorFactory factory = mock(InjectorFactory.class);
81 SimpleInjector injector = new SimpleInjector(factory);
82 final MySingleton singleton = new MySingleton();
83 when(factory.create(MyPojo.class)).thenReturn(new Injector() {
85 public void inject(Object aComponent) {
86 MyPojo pojo2 = (MyPojo) aComponent;
87 pojo2.setSingleton(singleton);
91 injector.inject(pojo);
92 // verify the custom injector was called.
93 assertSame(singleton, pojo.getSingleton());
97 public static class Y {
101 public static class X {
108 public void testInjectStorage() throws Exception {
110 InjectorBuilder.setInjectorFactory(null);
111 InjectorBuilder.getInjector().inject(x);
115 public void testInjectStorage2() {
117 InjectorBuilder.setInjectorFactory(null);
118 InjectorBuilder.getInjector().inject(x);