开发者

Junit: Test Spring (auto)wiring with reflection?

开发者 https://www.devze.com 2022-12-24 05:58 出处:网络
Is it possible to JUnit test if wiring by Spring is succesfully? I would like to do this by reflection. Like: get all beans with id *Controller and test if the fields *services are开发者_如何学Python

Is it possible to JUnit test if wiring by Spring is succesfully?

I would like to do this by reflection. Like: get all beans with id *Controller and test if the fields *services are开发者_如何学Python not null?

Thank you!


A better way is to annotate the setter methods with org.springframework.beans.factory.annotation.Required, and add the required annotations 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" />

If you want to verify that methods that match a certain pattern have the @Required annotation, implement a compiler hook, an AnnotationProcessor, that causes a compiler failure if methods matching a certain pattern aren't annotated with @Required.


  • build your ApplicationContext either via XmlWebApplicationContext's constructor or via the spring JUnit test runner and make your test implement ApplicationContextAware

  • use the methods of ApplicationContext to find and verify everything you need, with the help of ReflectionUtils and ReflectionTestUtils. But have in mind that if injection fails, the whole context initialization fails.

0

精彩评论

暂无评论...
验证码 换一张
取 消