View Javadoc
1   package mockit;
2   
3   import static java.util.Arrays.asList;
4   
5   import static org.junit.jupiter.api.Assertions.assertEquals;
6   import static org.junit.jupiter.api.Assertions.assertFalse;
7   
8   import java.util.ArrayList;
9   import java.util.HashSet;
10  import java.util.List;
11  import java.util.Set;
12  
13  import javax.enterprise.inject.Instance;
14  import javax.inject.Inject;
15  
16  import org.junit.jupiter.api.Test;
17  
18  /**
19   * The Class InstanceDITest.
20   */
21  final class InstanceDITest {
22  
23      /**
24       * The Class Collaborator.
25       */
26      static class Collaborator {
27      }
28  
29      /**
30       * The Class TestedClassWithInstanceInjectionPoints.
31       */
32      static final class TestedClassWithInstanceInjectionPoints {
33  
34          /** The names. */
35          final Set<String> names;
36  
37          /** The collaborators. */
38          @Inject
39          Instance<Collaborator> collaborators;
40  
41          /**
42           * Instantiates a new tested class with instance injection points.
43           *
44           * @param names
45           *            the names
46           */
47          @Inject
48          TestedClassWithInstanceInjectionPoints(Instance<String> names) {
49              this.names = new HashSet<>();
50  
51              for (String name : names) {
52                  this.names.add(name);
53              }
54          }
55      }
56  
57      /** The tested. */
58      @Tested
59      TestedClassWithInstanceInjectionPoints tested;
60  
61      /** The col 1. */
62      @Injectable
63      Collaborator col1;
64  
65      /** The col 2. */
66      @Injectable
67      Collaborator col2;
68  
69      /** The names. */
70      @Injectable
71      final Iterable<String> names = asList("Abc", "Test", "123");
72  
73      /**
74       * Allow multiple injectables of same type to be obtained from instance injection point.
75       */
76      @Test
77      void allowMultipleInjectablesOfSameTypeToBeObtainedFromInstanceInjectionPoint() {
78          assertEquals(new HashSet<>(asList("Abc", "Test", "123")), tested.names);
79  
80          Instance<Collaborator> collaborators = tested.collaborators;
81          assertFalse(collaborators.isAmbiguous());
82          assertFalse(collaborators.isUnsatisfied());
83  
84          List<Collaborator> collaboratorInstances = toList(collaborators);
85          assertEquals(asList(col1, col2), collaboratorInstances);
86      }
87  
88      /**
89       * To list.
90       *
91       * @param <T>
92       *            the generic type
93       * @param instances
94       *            the instances
95       *
96       * @return the list
97       */
98      static <T> List<T> toList(Iterable<T> instances) {
99          List<T> list = new ArrayList<>();
100 
101         for (T instance : instances) {
102             list.add(instance);
103         }
104 
105         return list;
106     }
107 }