AnnotatedFieldRetriever { public Set<Field> getAnnotatedFields(Class<?> clazz, Class<? extends Annotation> annotationClass) { Set<Field> mockDependentFields = new HashSet<Field>(); while (clazz != Object.class) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (null != field.getAnnotation(annotationClass)) { mockDependentFields.add(field); } } clazz = clazz.getSuperclass(); } return mockDependentFields; }  Set<Field> getAnnotatedFields(Class<?> clazz, Class<? extends Annotation> annotationClass);  }
@Test public void shouldGetAnnotatedFieldsGivenPrivateField() { Class<ClassWithAnnnotations> clazz = ClassWithAnnnotations.class; Class<? extends Annotation> annotationClass = InjectMocks.class; Set<Field> fields = retriever.getAnnotatedFields(clazz, annotationClass); assertEquals(1, fields.size()); assertTrue(fields.contains(getField(clazz, "privateAnnotatedField"))); }
@Test public void shouldGetAnnotatedFieldsGivenProtectedField() { Class<ClassWithAnnnotations> clazz = ClassWithAnnnotations.class; Class<? extends Annotation> annotationClass = Mock.class; Set<Field> fields = retriever.getAnnotatedFields(clazz, annotationClass); assertEquals(1, fields.size()); assertTrue(fields.contains(getField(clazz, "protectedAnnotatedField"))); }
@Test public void shouldGetAnnotatedFieldsGivenPublicField() { Class<ClassWithAnnnotations> clazz = ClassWithAnnnotations.class; Class<? extends Annotation> annotationClass = CollectionOfMocks.class; Set<Field> fields = retriever.getAnnotatedFields(clazz, annotationClass); assertEquals(1, fields.size()); assertTrue(fields.contains(getField(clazz, "publicAnnotatedField"))); }
@Test public void shouldGetAnnotatedFieldsGivenPackageField() { Class<ClassWithAnnnotations> clazz = ClassWithAnnnotations.class; Class<? extends Annotation> annotationClass = Spy.class; Set<Field> fields = retriever.getAnnotatedFields(clazz, annotationClass); assertEquals(1, fields.size()); assertTrue(fields.contains(getField(clazz, "defaultAnnotatedField"))); }
@Test public void shouldGetAnnotatedFieldsGivenExtendedClass() { Class<ExtendedClassWithAnnnotations> clazz = ExtendedClassWithAnnnotations.class; Class<? extends Annotation> annotationClass = InjectMocks.class; Set<Field> fields = retriever.getAnnotatedFields(clazz, annotationClass); assertEquals(2, fields.size()); assertTrue(fields.contains(getField(clazz, "privateAnnotatedField"))); assertTrue(fields.contains(getField(ClassWithAnnnotations.class, "privateAnnotatedField"))); }