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.test.inject;
18 import static junit.framework.Assert.*;
19 import static org.mockito.Mockito.*;
21 import java.lang.annotation.ElementType;
22 import java.lang.annotation.Retention;
23 import java.lang.annotation.RetentionPolicy;
24 import java.lang.annotation.Target;
25 import java.util.logging.ConsoleHandler;
26 import java.util.logging.Level;
28 import javax.persistence.EntityManager;
29 import javax.persistence.PersistenceContext;
31 import org.junit.Before;
32 import org.junit.Test;
33 import org.mockito.Mock;
34 import org.wamblee.inject.InjectorBuilder;
35 import org.wamblee.reflection.ObjectTraversal;
37 public class JavaEETestInjectorFactoryTest {
41 ObjectTraversal.LOGGER.setLevel(Level.FINEST);
42 ConsoleHandler handler = new ConsoleHandler();
43 handler.setLevel(Level.FINEST);
44 ObjectTraversal.LOGGER.addHandler(handler);
47 public static final class X {
50 private EntityManager entityManager;
52 private EntityManager entityManager2;
55 public EntityManager getEntityManager() {
56 return entityManager2;
59 public void setEntityManager(EntityManager aEm) {
65 public void testXyz() {
66 EntityManager em = mock(EntityManager.class);
67 InjectorBuilder.setInjectorFactory(new JavaEETestInjectorFactory()
68 .addEntityManagerBinding(em));
72 assertNull(x.entityManager);
73 assertNull(x.entityManager2);
74 InjectorBuilder.getInjector().inject(x);
77 assertSame(em, x.entityManager);
78 assertSame(em, x.entityManager2);
82 public static class Y {
84 private Integer wrongType;
88 public void testWrongType() {
89 EntityManager em = mock(EntityManager.class);
90 InjectorBuilder.setInjectorFactory(new JavaEETestInjectorFactory()
91 .addEntityManagerBinding(em));
93 InjectorBuilder.getInjector().inject(y);
94 assertNull(y.wrongType);
97 @Retention(RetentionPolicy.RUNTIME)
98 @Target( { ElementType.FIELD, ElementType.METHOD })
99 public static @interface MyAnnotation {
103 public static class Z {
107 // any annotation will force traversal.
114 public void testCustomInjection() {
115 JavaEETestInjectorFactory factory = new JavaEETestInjectorFactory();
116 factory.addBinding(new Binding(int.class, MyAnnotation.class, 100));
117 InjectorBuilder.setInjectorFactory(factory);
121 assertEquals(0, z.x);
122 InjectorBuilder.getInjector().inject(z);
123 assertEquals(100, z.x);
124 assertEquals(100, z.z.x);