org.mockito.InjectMocks Java Examples

The following examples show how to use org.mockito.InjectMocks. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestMockito.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Replies the type of features in this test that could be or are mocked.
 * A mockable feature is a field that has one of the following annotations:
 * {@link Mock}, {@link InjectMocks}. If the feature is annotation with
 * {@link ManualMocking}, is it not considered by this function.
 *
 * @param typeToExplore is the type to explore.
 * @return the type of mockable features. If it is {@code 0}, no mockable feature was found.
 */
public static int getAutomaticMockableFeatures(Class<?> typeToExplore) {
	int features = 0;
	Class<?> type = typeToExplore;
	while (type != null && !AbstractSarlTest.class.equals(type)) {
		if (type.getAnnotation(ManualMocking.class) != null) {
			return 0;
		}
		for (Field field : type.getDeclaredFields()) {
			if (field.getAnnotation(Mock.class) != null) {
				features |= 0x1;
			} else if (field.getAnnotation(InjectMocks.class) != null) {
				features |= 0x2;
			}
		}
		type = type.getSuperclass();
	}
	return features;
}
 
Example #2
Source File: FieldInitializerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void shouldNotFailIfLocalTypeFieldIsInstantiated() throws Exception {
    // when
    class LocalType { };

    class TheTestWithLocalType {
        @InjectMocks LocalType field = new LocalType();
    }

    TheTestWithLocalType testWithLocalType = new TheTestWithLocalType();

    // when
    new FieldInitializer(testWithLocalType, testWithLocalType.getClass().getDeclaredField("field"));
}
 
Example #3
Source File: FieldInitializerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_not_fail_if_local_type_field_is_instantiated() throws Exception {
    // when
    class LocalType { }

    class TheTestWithLocalType {
        @InjectMocks LocalType field = new LocalType();
    }

    TheTestWithLocalType testWithLocalType = new TheTestWithLocalType();

    // when
    new FieldInitializer(testWithLocalType, testWithLocalType.getClass().getDeclaredField("field"));
}
 
Example #4
Source File: FieldInitializerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected = MockitoException.class)
public void should_fail_for_local_type_field() throws Exception {
    // when
    class LocalType { }

    class TheTestWithLocalType {
        @InjectMocks LocalType field;
    }

    TheTestWithLocalType testWithLocalType = new TheTestWithLocalType();

    // when
    new FieldInitializer(testWithLocalType, testWithLocalType.getClass().getDeclaredField("field"));
}
 
Example #5
Source File: MockInjectionUsingSetterOrPropertyTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldReportNicely() throws Exception {
    Object failing = new Object() {
        @InjectMocks ThrowingConstructor failingConstructor;
    };
    try {
        MockitoAnnotations.initMocks(failing);
        fail();
    } catch (MockitoException e) {
        Assertions.assertThat(e.getMessage()).contains("failingConstructor").contains("constructor").contains("threw an exception");
        Assertions.assertThat(e.getCause()).isInstanceOf(RuntimeException.class);
    }
}
 
Example #6
Source File: InjectMocksScanner.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
void assertNoAnnotations(final Field field, final Class... annotations) {
    for (Class annotation : annotations) {
        if (field.isAnnotationPresent(annotation)) {
            new Reporter().unsupportedCombinationOfAnnotations(annotation.getSimpleName(), InjectMocks.class.getSimpleName());
        }
    }
}
 
Example #7
Source File: InjectMocksScanner.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Scan fields annotated by &#064;InjectMocks
 *
 * @return Fields that depends on Mock
 */
private Set<Field> scan() {
    Set<Field> mockDependentFields = new HashSet<Field>();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        if (null != field.getAnnotation(InjectMocks.class)) {
            assertNoAnnotations(field, Mock.class, MockitoAnnotations.Mock.class, Captor.class);
            mockDependentFields.add(field);
        }
    }

    return mockDependentFields;
}
 
Example #8
Source File: UnitTestDependencyInjectionTestExecutionListener.java    From wisp with Apache License 2.0 5 votes vote down vote up
@Override
protected void injectDependencies(TestContext testContext) throws Exception {
    super.injectDependencies(testContext);
    /**
     * 获取测试类 & fields
     */
    Object bean = testContext.getTestInstance();
    List<Field> fields = getDeclaredFields(bean);
    if (CollectionUtils.isEmpty(fields)) {
        return;
    }
    /**
     * 如果测试类中, 被测试对象含有mockito的@InjectMocks注解,且 被测试对象被事务拦截器拦截 则 用原始对象代替
     */
    for (Field field : fields) {
        InjectMocks injectMocks = field.getAnnotation(InjectMocks.class);
        if (injectMocks == null) {
            continue;
        }
        field.setAccessible(true);
        Object proxy = field.get(bean);
        if (AopUtils.isAopProxy(proxy)) {
            // 替换对象
            Object target = ((Advised) proxy).getTargetSource().getTarget();
            field.set(bean, target);
        }
    }
}
 
Example #9
Source File: FieldInitializerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected = MockitoException.class)
public void shouldFailForLocalTypeField() throws Exception {
    // when
    class LocalType { };

    class TheTestWithLocalType {
        @InjectMocks LocalType field;
    }

    TheTestWithLocalType testWithLocalType = new TheTestWithLocalType();

    // when
    new FieldInitializer(testWithLocalType, testWithLocalType.getClass().getDeclaredField("field"));
}
 
Example #10
Source File: MockInjectionTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldReportNicely() throws Exception {
    Object failing = new Object() {
        @InjectMocks
        ThrowingConstructor c;
    };
    try {
        MockitoAnnotations.initMocks(failing);
        fail();
    } catch (MockitoException e) {
        assertContains("correct usage of @InjectMocks", e.getMessage());
    }
}
 
Example #11
Source File: TestMockito.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Replies if the given field could be reset with {@code null}.
 * If the given field is annoted with {@link Mock} or {@link InjectMocks},
 * or any annotation with the name {@code "Nullable"} or
 * {@code "NonNullByDefault"}, then the field is nullable.
 *
 * @param field the field to test.
 * @return {@code true} if the given field could be reset.
 */
public static boolean isNullable(Field field) {
	if (field.getAnnotation(Mock.class) != null
			|| field.getAnnotation(InjectMocks.class) != null) {
		return true;
	}
	for (Annotation annotation : field.getAnnotations()) {
		if ("Nullable".equals(annotation.annotationType().getSimpleName())
				|| "NonNullByDefault".equals(annotation.annotationType().getSimpleName())) {
			return true;
		}
	}
	return false;
}
 
Example #12
Source File: WrongSetOfAnnotationsTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test(expected=MockitoException.class)
public void shouldNotAllowCaptorAndInjectMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @InjectMocks @Captor ArgumentCaptor captor;
    });
}
 
Example #13
Source File: WrongSetOfAnnotationsTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test(expected=MockitoException.class)
public void shouldNotAllowMockAndInjectMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @InjectMocks @Mock List mock;
    });
}
 
Example #14
Source File: WrongSetOfAnnotationsTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test(expected=MockitoException.class)
public void shouldNotAllowSpyAndInjectMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @InjectMocks @Spy List mock;
    });
}
 
Example #15
Source File: WrongSetOfAnnotationsTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test(expected=MockitoException.class)
public void shouldNotAllowSpyAndInjectMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @InjectMocks @Spy List mock;
    });
}
 
Example #16
Source File: WrongSetOfAnnotationsTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test(expected=MockitoException.class)
public void shouldNotAllowMockAndInjectMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @InjectMocks @Mock List mock;
    });
}
 
Example #17
Source File: WrongSetOfAnnotationsTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test(expected=MockitoException.class)
public void shouldNotAllowCaptorAndInjectMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @InjectMocks @Captor ArgumentCaptor captor;
    });
}
 
Example #18
Source File: UnitTestDependencyInjectionTestExecutionListener.java    From wisp with Apache License 2.0 4 votes vote down vote up
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
    super.afterTestMethod(testContext);

    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) testContext.getApplicationContext()
            .getAutowireCapableBeanFactory();

    /**
     * 方法结束后记录被测试对象的bean名称
     */
    Object bean = testContext.getTestInstance();
    List<Field> fields = getDeclaredFields(bean);
    for (Field field : fields) {
        InjectMocks injectMocks = field.getAnnotation(InjectMocks.class);
        if (injectMocks == null) {
            continue;
        }
        Object testedBean = null;
        String testedBeanName = null;
        /**
         * 被测试的对象如果通过spring自动注入,则记录
         * 两种注入方式 Autowired
         * Resource
         */
        if (field.getAnnotation(Autowired.class) != null) {
            Qualifier qualifier = field.getAnnotation(Qualifier.class);
            testedBean = qualifier == null ? beanFactory.getBean(field.getType())
                    : beanFactory.getBean(qualifier.value());
            testedBeanName = qualifier == null ? beanFactory.getBeanNamesForType(field.getType())[0]
                    : qualifier.value();
        } else if (field.getAnnotation(Resource.class) != null) {
            Resource resource = field.getAnnotation(Resource.class);
            Class<?> type = resource.type();
            String name = resource.name();
            if (StringUtils.isNotEmpty(name)) {
                testedBean = beanFactory.getBean(name);
                testedBeanName = name;
            } else {
                testedBean = (type != Object.class) ? beanFactory.getBean(type)
                        : beanFactory.getBean(field.getType());
                testedBeanName = (type != Object.class) ? beanFactory.getBeanNamesForType(type)[0]
                        : beanFactory.getBeanNamesForType(field.getType())[0];
            }
        }

        if (testedBean != null) {
            testedObjects.put(testedBeanName, testedBean);
        }
    }
}