1 /* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 package org.mockito.internal.configuration.injection.scanner; 6 7 import org.mockito.Captor; 8 import org.mockito.InjectMocks; 9 import org.mockito.Mock; 10 11 import static org.mockito.internal.exceptions.Reporter.unsupportedCombinationOfAnnotations; 12 13 import java.lang.annotation.Annotation; 14 import java.lang.reflect.Field; 15 import java.util.HashSet; 16 import java.util.Set; 17 18 /** 19 * Scan field for injection. 20 */ 21 public class InjectMocksScanner { 22 private final Class<?> clazz; 23 24 /** 25 * Create a new InjectMocksScanner for the given clazz on the given instance 26 * 27 * @param clazz Current class in the hierarchy of the test 28 */ 29 public InjectMocksScanner(Class<?> clazz) { 30 this.clazz = clazz; 31 } 32 33 34 /** 35 * Add the fields annotated by @{@link InjectMocks} 36 * 37 * @param mockDependentFields Set of fields annotated by @{@link InjectMocks} 38 */ 39 public void addTo(Set<Field> mockDependentFields) { 40 mockDependentFields.addAll(scan()); 41 } 42 43 /** 44 * Scan fields annotated by @InjectMocks 45 * 46 * @return Fields that depends on Mock 47 */ 48 @SuppressWarnings("unchecked") 49 private Set<Field> scan() { 50 Set<Field> mockDependentFields = new HashSet<Field>(); 51 Field[] fields = clazz.getDeclaredFields(); 52 for (Field field : fields) { 53 if (null != field.getAnnotation(InjectMocks.class)) { 54 assertNoAnnotations(field, Mock.class, Captor.class); 55 mockDependentFields.add(field); 56 } 57 } 58 59 return mockDependentFields; 60 } 61 62 private static void assertNoAnnotations(Field field, Class<? extends Annotation>... annotations) { 63 for (Class<? extends Annotation> annotation : annotations) { 64 if (field.isAnnotationPresent(annotation)) { 65 throw unsupportedCombinationOfAnnotations(annotation.getSimpleName(), InjectMocks.class.getSimpleName()); 66 } 67 } 68 } 69 } 70