我有一个与数据库通信的Spring Bean类,我正在为它编写一个测试用例。
我正在使用DbUnit,它使用JUnit Annotation @Before 设置内存数据库(基于扩展基础DbUnit类)。
问题在于我正在尝试测试的 @Autowired bean:它在 @Postconstruct 方法中访问数据库,这发生在DB Setup之前,注意该类本身用 @Component 注释。
因此,我需要使用一种方法或注释,以便我正在测试的bean只有在@Before JUnit方法运行后才会被初始化。
答案 0 :(得分:2)
这是弹簧的常见问题,并且有解决它的常见解决方案。 你需要建立所谓的三期建设"。
通常,只有在设置了所有弹簧上下文(使用数据库)后才想初始化bean。所以你需要在初始化spring时监听,然后执行你的逻辑。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface PostProxy {
}
此类应该在您的上下文中定义为bean。
public class PostProxySpringContextListener implements ApplicationListener<ContextRefreshedEvent> {
private static Logger LOG = LoggerFactory.getLogger(PostProxySpringContextListener.class);
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext context = event.getApplicationContext();
String[] beanDefinitionNames = context.getBeanDefinitionNames();
for (String beanDefinitionName : beanDefinitionNames) {
String originalClassName = getOriginalClassName(beanDefinitionName, event);
if (originalClassName != null) {
invokeAnnotatedMethods(context, beanDefinitionName, originalClassName);
}
}
}
private String getOriginalClassName(String name, ContextRefreshedEvent event) {
try {
ConfigurableListableBeanFactory factory =
(ConfigurableListableBeanFactory)event.getApplicationContext().getAutowireCapableBeanFactory();
BeanDefinition beanDefinition = factory.getBeanDefinition(name);
return beanDefinition.getBeanClassName();
} catch (NoSuchBeanDefinitionException e) {
LOG.debug("Can't get bean definition for : " + name);
return null;
}
}
private void invokeAnnotatedMethods(ApplicationContext context, String beanDefinitionName, String originalClassName) {
try {
Class<?> originalClass = Class.forName(originalClassName);
Method[] methods = originalClass.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(PostProxy.class)) {
LOG.info("Executing @PostProxy annotated initialization method: " + method.toString());
Object bean = context.getBean(beanDefinitionName);
Method currentMethod = bean.getClass().getMethod(method.getName(), method.getParameterTypes());
currentMethod.invoke(bean);
}
}
} catch (ClassNotFoundException e) {
LOG.trace("No class instance for bean " + beanDefinitionName + " with class name " + originalClassName);
} catch (NoSuchMethodException e) {
LOG.error("Error finding @PostProxy method for bean " + beanDefinitionName, e);
} catch (InvocationTargetException e) {
LOG.error("Error invoking @PostProxy method for bean " + beanDefinitionName, e);
} catch (IllegalAccessException e) {
LOG.error("Can't invoke annotated method in bean" + beanDefinitionName + " with class name " + originalClassName
+ ". Please check access modifiers on @PostProxy methods.", e);
}
}
}