PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/core/test/com/google/inject/RequestInjectionTest.java

https://gitlab.com/metamorphiccode/guice
Java | 235 lines | 170 code | 32 blank | 33 comment | 0 complexity | 46f664bca657f52697c8f21a28dc2f8e MD5 | raw file
  1. /**
  2. * Copyright (C) 2006 Google Inc.
  3. *
  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
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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.
  15. */
  16. package com.google.inject;
  17. import static com.google.inject.Asserts.assertContains;
  18. import static com.google.inject.Asserts.getDeclaringSourcePart;
  19. import static java.lang.annotation.RetentionPolicy.RUNTIME;
  20. import com.google.inject.matcher.Matchers;
  21. import com.google.inject.spi.TypeEncounter;
  22. import com.google.inject.spi.TypeListener;
  23. import junit.framework.TestCase;
  24. import java.lang.annotation.Retention;
  25. /**
  26. * @author crazybob@google.com (Bob Lee)
  27. */
  28. public class RequestInjectionTest extends TestCase {
  29. @Retention(RUNTIME)
  30. @BindingAnnotation @interface ForField {}
  31. @Retention(RUNTIME)
  32. @BindingAnnotation @interface ForMethod {}
  33. @Override
  34. protected void setUp() throws Exception {
  35. super.setUp();
  36. HasInjections.staticField = 0;
  37. HasInjections.staticMethod = null;
  38. }
  39. public void testInjectMembers() {
  40. final HasInjections hi = new HasInjections();
  41. Guice.createInjector(new AbstractModule() {
  42. @Override
  43. protected void configure() {
  44. bindConstant().annotatedWith(ForMethod.class).to("test");
  45. bindConstant().annotatedWith(ForField.class).to(5);
  46. requestInjection(hi);
  47. }
  48. });
  49. assertEquals("test", hi.instanceMethod);
  50. assertEquals(5, hi.instanceField);
  51. assertNull(HasInjections.staticMethod);
  52. assertEquals(0, HasInjections.staticField);
  53. }
  54. public void testInjectStatics() throws CreationException {
  55. Guice.createInjector(new AbstractModule() {
  56. @Override
  57. protected void configure() {
  58. bindConstant().annotatedWith(ForMethod.class).to("test");
  59. bindConstant().annotatedWith(ForField.class).to(5);
  60. requestStaticInjection(HasInjections.class);
  61. }
  62. });
  63. assertEquals("test", HasInjections.staticMethod);
  64. assertEquals(5, HasInjections.staticField);
  65. }
  66. public void testInjectMembersAndStatics() {
  67. final HasInjections hi = new HasInjections();
  68. Guice.createInjector(new AbstractModule() {
  69. @Override
  70. protected void configure() {
  71. bindConstant().annotatedWith(ForMethod.class).to("test");
  72. bindConstant().annotatedWith(ForField.class).to(5);
  73. requestStaticInjection(HasInjections.class);
  74. requestInjection(hi);
  75. }
  76. });
  77. assertEquals("test", hi.instanceMethod);
  78. assertEquals(5, hi.instanceField);
  79. assertEquals("test", HasInjections.staticMethod);
  80. assertEquals(5, HasInjections.staticField);
  81. }
  82. public void testValidationErrorOnInjectedMembers() {
  83. try {
  84. Guice.createInjector(new AbstractModule() {
  85. @Override
  86. protected void configure() {
  87. requestInjection(new NeedsRunnable());
  88. }
  89. });
  90. } catch (CreationException expected) {
  91. assertContains(expected.getMessage(),
  92. "1) No implementation for java.lang.Runnable was bound",
  93. "at " + NeedsRunnable.class.getName(), ".runnable(RequestInjectionTest.java:");
  94. }
  95. }
  96. public void testInjectionErrorOnInjectedMembers() {
  97. try {
  98. Guice.createInjector(new AbstractModule() {
  99. @Override
  100. protected void configure() {
  101. bind(Runnable.class).toProvider(new Provider<Runnable>() {
  102. public Runnable get() {
  103. throw new UnsupportedOperationException();
  104. }
  105. });
  106. requestInjection(new NeedsRunnable());
  107. }
  108. });
  109. } catch (CreationException expected) {
  110. assertContains(expected.getMessage(),
  111. "1) Error in custom provider, java.lang.UnsupportedOperationException",
  112. "for field at " + NeedsRunnable.class.getName() + ".runnable(RequestInjectionTest.java:",
  113. "at " + getClass().getName(), getDeclaringSourcePart(getClass()));
  114. }
  115. }
  116. public void testUserExceptionWhileInjectingInstance() {
  117. try {
  118. Guice.createInjector(new AbstractModule() {
  119. @Override
  120. protected void configure() {
  121. requestInjection(new BlowsUpOnInject());
  122. }
  123. });
  124. fail();
  125. } catch (CreationException expected) {
  126. assertContains(expected.getMessage(),
  127. "1) Error injecting method, java.lang.UnsupportedOperationException: Pop",
  128. "at " + BlowsUpOnInject.class.getName() + ".injectInstance(RequestInjectionTest.java:");
  129. }
  130. }
  131. public void testUserExceptionWhileInjectingStatically() {
  132. try {
  133. Guice.createInjector(new AbstractModule() {
  134. @Override
  135. protected void configure() {
  136. requestStaticInjection(BlowsUpOnInject.class);
  137. }
  138. });
  139. fail();
  140. } catch (CreationException expected) {
  141. assertContains(expected.getMessage(),
  142. "1) Error injecting method, java.lang.UnsupportedOperationException: Snap",
  143. "at " + BlowsUpOnInject.class.getName() + ".injectStatically(RequestInjectionTest.java:");
  144. }
  145. }
  146. static class NeedsRunnable {
  147. @Inject Runnable runnable;
  148. }
  149. static class HasInjections {
  150. @Inject @ForField static int staticField;
  151. @Inject @ForField int instanceField;
  152. static String staticMethod;
  153. String instanceMethod;
  154. @Inject static void setStaticMethod(@ForMethod String staticMethod) {
  155. HasInjections.staticMethod = staticMethod;
  156. }
  157. @Inject void setInstanceS(@ForMethod String instanceS) {
  158. this.instanceMethod = instanceS;
  159. }
  160. }
  161. static class BlowsUpOnInject {
  162. @Inject void injectInstance() {
  163. throw new UnsupportedOperationException("Pop");
  164. }
  165. @Inject static void injectStatically() {
  166. throw new UnsupportedOperationException("Snap");
  167. }
  168. }
  169. /*
  170. * Tests that initializables of the same instance don't clobber
  171. * membersInjectors in InitializableReference, so that they ultimately
  172. * can be requested in any order.
  173. */
  174. public void testEarlyInjectableReferencesWithSameIdentity() {
  175. Injector injector = Guice.createInjector(new AbstractModule() {
  176. @Override
  177. protected void configure() {
  178. // Add a listener to trigger all toInstance bindings to get an Initializable.
  179. bindListener(Matchers.any(), new TypeListener() {
  180. @Override
  181. public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
  182. }
  183. });
  184. // Bind two different Keys to the IDENTITICAL object
  185. // ORDER MATTERS! We want the String binding to push out the Object one
  186. String fail = new String("better not fail!");
  187. bind(Object.class).toInstance(fail);
  188. bind(String.class).toInstance(fail);
  189. // Then try to inject those objects in a requestInjection,
  190. // letting us get into InjectableReference.get before it has
  191. // finished running through all its injections.
  192. // Each of these technically has its own InjectableReference internally.
  193. // ORDER MATTERS!.. because Object is injected first, that InjectableReference
  194. // attempts to process its members injector, but it wasn't initialized,
  195. // because String pushed it out of the queue!
  196. requestInjection(new Object() {
  197. @SuppressWarnings("unused") @Inject Object obj;
  198. @SuppressWarnings("unused") @Inject String str;
  199. });
  200. }
  201. });
  202. }
  203. }