Junit:用反射测试弹簧(自动)接线?

时间:2010-03-22 15:20:43

标签: java unit-testing spring reflection junit

如果Spring成功连接,是否可以进行JUnit测试?

我想通过反思来做到这一点。喜欢:获取标识为*Controller的所有bean并测试字段*services是否为空?

谢谢!

2 个答案:

答案 0 :(得分:4)

更好的方法是使用org.springframework.beans.factory.annotation.Required注释setter方法,并在post processor下添加所需的注释:

<!--
    This bean will cause an error if you forget to supply any properties
    annotated with @Required on the setter method; this is good for
    catching errors.
-->
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />

如果要验证与某个模式匹配的方法是否具有@Required注释,请实现编译器挂钩,AnnotationProcessor,如果未使用@Required注释匹配某个模式的方法,则会导致编译器失败。

答案 1 :(得分:2)

  • 通过ApplicationContext的构造函数或spring JUnit test runner构建XmlWebApplicationContext并制作测试工具ApplicationContextAware

  • ApplicationContextReflectionUtils的帮助下,使用ReflectionTestUtils的方法查找并验证您需要的所有内容。但请记住,如果注入失败,整个上下文初始化将失败。

相关问题