如果Spring成功连接,是否可以进行JUnit测试?
我想通过反思来做到这一点。喜欢:获取标识为*Controller
的所有bean并测试字段*services
是否为空?
谢谢!
答案 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
在ApplicationContext
和ReflectionUtils
的帮助下,使用ReflectionTestUtils
的方法查找并验证您需要的所有内容。但请记住,如果注入失败,整个上下文初始化将失败。