Java Code Examples for org.mockito.InjectMocks

The following examples show how to use org.mockito.InjectMocks. These examples are extracted from open source projects. 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 Project: sarl   Source File: TestMockito.java    License: 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
@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 3
Source Project: sarl   Source File: TestMockito.java    License: 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 4
Source Project: astor   Source File: MockInjectionTest.java    License: 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 5
Source Project: astor   Source File: FieldInitializerTest.java    License: 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 6
Source Project: astor   Source File: FieldInitializerTest.java    License: 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 7
Source Project: astor   Source File: InjectMocksScanner.java    License: 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 Project: astor   Source File: InjectMocksScanner.java    License: 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 9
@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 10
Source Project: astor   Source File: FieldInitializerTest.java    License: 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 11
Source Project: astor   Source File: FieldInitializerTest.java    License: 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 12
@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);
        }
    }
}
 
Example 13
@Test(expected=MockitoException.class)
public void shouldNotAllowSpyAndInjectMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @InjectMocks @Spy List mock;
    });
}
 
Example 14
@Test(expected=MockitoException.class)
public void shouldNotAllowMockAndInjectMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @InjectMocks @Mock List mock;
    });
}
 
Example 15
@Test(expected=MockitoException.class)
public void shouldNotAllowCaptorAndInjectMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @InjectMocks @Captor ArgumentCaptor captor;
    });
}
 
Example 16
@Test(expected=MockitoException.class)
public void shouldNotAllowSpyAndInjectMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @InjectMocks @Spy List mock;
    });
}
 
Example 17
@Test(expected=MockitoException.class)
public void shouldNotAllowMockAndInjectMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @InjectMocks @Mock List mock;
    });
}
 
Example 18
@Test(expected=MockitoException.class)
public void shouldNotAllowCaptorAndInjectMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @InjectMocks @Captor ArgumentCaptor captor;
    });
}