aboutsummaryrefslogtreecommitdiff
path: root/core/test/com/google/inject/name/NamedEquivalanceTest.java
blob: 58a6a90914f26f0e69d0907ec3c593e40d07a250 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/**
 * Copyright (C) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.inject.name;

import static com.google.inject.Asserts.assertContains;

import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.util.Properties;

import junit.framework.TestCase;

import com.google.inject.AbstractModule;
import com.google.inject.ConfigurationException;
import com.google.inject.CreationException;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provides;

/**
 * Tests that {@code javax.inject.Named} and {@code com.google.inject.name.Named} are completely
 * interchangeable: bindings for one can be used to inject the other.
 * 
 * @author cgdecker@gmail.com (Colin Decker)
 */
public class NamedEquivalanceTest extends TestCase {

  private static final Module GUICE_BINDING_MODULE = moduleWithAnnotation(Names.named("foo"));
  private static final Module JSR330_BINDING_MODULE = moduleWithAnnotation(new JsrNamed("foo"));
  private static final Module GUICE_PROVIDER_METHOD_MODULE = getGuiceBindingProviderMethodModule();
  private static final Module JSR330_PROVIDER_METHOD_MODULE = getJsr330BindingProviderMethodModule();

  public void testKeysCreatedWithDifferentTypesAreEqual() {
    assertEquals(keyForAnnotation(new GuiceNamed("foo")), keyForAnnotation(new JsrNamed("foo")));
    assertEquals(keyForAnnotation(Names.named("foo")), keyForAnnotation(new GuiceNamed("foo")));
    assertEquals(keyForAnnotation(Names.named("foo")), keyForAnnotation(new JsrNamed("foo")));

    assertEquals(keyForAnnotationType(com.google.inject.name.Named.class),
        keyForAnnotationType(javax.inject.Named.class));
  }

  private static Key<String> keyForAnnotation(Annotation annotation) {
    return Key.get(String.class, annotation);
  }
  
  private static Key<String> keyForAnnotationType(Class<? extends Annotation> annotationType) {
    return Key.get(String.class, annotationType);
  }

  public void testBindingWithNamesCanInjectBothTypes() {
    assertInjectionsSucceed(GUICE_BINDING_MODULE);
  }

  public void testBindingWithJsr330AnnotationCanInjectBothTypes() {
    assertInjectionsSucceed(JSR330_BINDING_MODULE);
  }

  public void testBindingWithGuiceNamedAnnotatedProviderMethodCanInjectBothTypes() {
    assertInjectionsSucceed(GUICE_PROVIDER_METHOD_MODULE);
  }

  public void testBindingWithJsr330NamedAnnotatedProviderMethodCanInjectBothTypes() {
    assertInjectionsSucceed(JSR330_PROVIDER_METHOD_MODULE);
  }

  public void testBindingDifferentTypesWithSameValueIsIgnored() {
    assertDuplicateBinding(GUICE_BINDING_MODULE, JSR330_BINDING_MODULE, false);
    assertDuplicateBinding(JSR330_BINDING_MODULE, GUICE_BINDING_MODULE, false);
  }

  public void testBindingDifferentTypesWithSameValueIsAnErrorWithProviderMethods() {
    assertDuplicateBinding(GUICE_PROVIDER_METHOD_MODULE, JSR330_PROVIDER_METHOD_MODULE, true);
    assertDuplicateBinding(JSR330_PROVIDER_METHOD_MODULE, GUICE_PROVIDER_METHOD_MODULE, true);
  }

  public void testBindingDifferentTypesWithSameValueIsAnErrorMixed() {
    assertDuplicateBinding(GUICE_BINDING_MODULE, JSR330_PROVIDER_METHOD_MODULE, true);
    assertDuplicateBinding(JSR330_BINDING_MODULE, GUICE_PROVIDER_METHOD_MODULE, true);
  }

  public void testMissingBindingForGuiceNamedUsesSameTypeInErrorMessage() {
    assertMissingBindingErrorMessageUsesType(GuiceNamedClient.class);
  }

  public void testMissingBindingForJsr330NamedUsesSameTypeInErrorMessage() {
    assertMissingBindingErrorMessageUsesType(Jsr330NamedClient.class);
  }

  public void testBindPropertiesWorksWithJsr330() {
    assertInjectionsSucceed(new AbstractModule() {
      @Override protected void configure() {
        Properties properties = new Properties();
        properties.put("foo", "bar");
        Names.bindProperties(binder(), properties);
      }
    });
  }

  private static void assertMissingBindingErrorMessageUsesType(Class<?> clientType) {
    try {
      Guice.createInjector().getInstance(clientType);
      fail("should have thrown ConfigurationException");
    } catch (ConfigurationException e) {
      assertContains(e.getMessage(),
          "No implementation for java.lang.String annotated with @com.google.inject.name.Named(value=foo) was bound.");
    }
  }

  private static void assertDuplicateBinding(Module a, Module b, boolean fails) {
    try {
      Guice.createInjector(a, b);
      if(fails) {
        fail("should have thrown CreationException");
      }
    } catch (CreationException e) {
      if(fails) {
        assertContains(e.getMessage(),
            "A binding to java.lang.String annotated with @com.google.inject.name.Named(value=foo) was already configured");
      } else {
        throw e;
      }
    }
  }

  private static Module moduleWithAnnotation(final Annotation annotation) {
    return new AbstractModule() {
      @Override protected void configure() {
        bindConstant().annotatedWith(annotation).to("bar");
      }
    };
  }

  private static void assertInjectionsSucceed(Module module) {
    Injector injector = Guice.createInjector(module);
    assertInjected(injector.getInstance(GuiceNamedClient.class), injector
        .getInstance(Jsr330NamedClient.class));
  }

  private static void assertInjected(GuiceNamedClient guiceClient, Jsr330NamedClient jsr330Client) {
    assertEquals("bar", guiceClient.foo);
    assertEquals("bar", jsr330Client.foo);
  }

  private static Module getJsr330BindingProviderMethodModule() {
    return new AbstractModule() {
      @Override protected void configure() {}
      @SuppressWarnings("unused") @Provides @javax.inject.Named("foo") String provideFoo() {
        return "bar";
      }
    };
  }

  private static Module getGuiceBindingProviderMethodModule() {
    return new AbstractModule() {
      @Override protected void configure() {}
      @SuppressWarnings("unused") @Provides @Named("foo") String provideFoo() {
        return "bar";
      }
    };
  }

  private static class GuiceNamedClient {
    @Inject @Named("foo") String foo;
  }

  private static class Jsr330NamedClient {
    @Inject @javax.inject.Named("foo") String foo;
  }

  private static class JsrNamed implements javax.inject.Named, Serializable {
    private final String value;

    public JsrNamed(String value) {
      this.value = value;
    }

    public String value() {
      return this.value;
    }

    public int hashCode() {
      // This is specified in java.lang.Annotation.
      return (127 * "value".hashCode()) ^ value.hashCode();
    }

    public boolean equals(Object o) {
      if (!(o instanceof javax.inject.Named)) {
        return false;
      }

      javax.inject.Named other = (javax.inject.Named) o;
      return value.equals(other.value());
    }

    public String toString() {
      return "@" + javax.inject.Named.class.getName() + "(value=" + value + ")";
    }

    public Class<? extends Annotation> annotationType() {
      return javax.inject.Named.class;
    }

    private static final long serialVersionUID = 0;
  }

  private static class GuiceNamed implements com.google.inject.name.Named, Serializable {
    private final String value;
    
    public GuiceNamed(String value) {
      this.value = value;
    }
    
    public String value() {
      return this.value;
    }
    
    public int hashCode() {
      // This is specified in java.lang.Annotation.
      return (127 * "value".hashCode()) ^ value.hashCode();
    }

    public boolean equals(Object o) {
      if (!(o instanceof com.google.inject.name.Named)) {
        return false;
      }

      com.google.inject.name.Named other = (com.google.inject.name.Named) o;
      return value.equals(other.value());
    }

    public String toString() {
      return "@" + com.google.inject.name.Named.class.getName() + "(value=" + value + ")";
    }

    public Class<? extends Annotation> annotationType() {
      return com.google.inject.name.Named.class;
    }

    private static final long serialVersionUID = 0;
  }
}