All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.fitbur.mockito.internal.configuration.injection.scanner.InjectMocksScanner Maven / Gradle / Ivy

There is a newer version: 1.0.0
Show newest version
/*
 * Copyright (c) 2007 Mockito contributors
 * This program is made available under the terms of the MIT License.
 */
package com.fitbur.mockito.internal.configuration.injection.scanner;

import com.fitbur.mockito.Captor;
import com.fitbur.mockito.InjectMocks;
import com.fitbur.mockito.Mock;
import com.fitbur.mockito.MockitoAnnotations;
import com.fitbur.mockito.exceptions.Reporter;

import static com.fitbur.mockito.exceptions.Reporter.unsupportedCombinationOfAnnotations;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

/**
 * Scan field for injection.
 */
public class InjectMocksScanner {
    private final Class clazz;

    /**
     * Create a new InjectMocksScanner for the given clazz on the given instance
     *
     * @param clazz    Current class in the hierarchy of the test
     */
    public InjectMocksScanner(Class clazz) {
        this.clazz = clazz;
    }


    /**
     * Add the fields annotated by @{@link InjectMocks}
     *
     * @param mockDependentFields Set of fields annotated by  @{@link InjectMocks}
     */
    public void addTo(Set mockDependentFields) {
        mockDependentFields.addAll(scan());
    }

    /**
     * Scan fields annotated by @InjectMocks
     *
     * @return Fields that depends on Mock
     */
    @SuppressWarnings("unchecked")
    private Set scan() {
        Set mockDependentFields = new HashSet();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (null != field.getAnnotation(InjectMocks.class)) {
                assertNoAnnotations(field, Mock.class, Captor.class);
                mockDependentFields.add(field);
            }
        }

        return mockDependentFields;
    }

    private static void assertNoAnnotations(Field field, Class... annotations) {
        for (Class annotation : annotations) {
            if (field.isAnnotationPresent(annotation)) {
                throw unsupportedCombinationOfAnnotations(annotation.getSimpleName(), InjectMocks.class.getSimpleName());
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy