@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);
}
}
}
UnitTestDependencyInjectionTestExecutionListener.java 文件源码
java
阅读 27
收藏 0
点赞 0
评论 0
项目:wisp
作者:
评论列表
文章目录