How configure correctly @RunWith(Parameterized.class) + SpringClassRule + SpringMethodRule with a custom @Rule?

自闭症网瘾萝莉.ら 提交于 2019-12-03 20:58:45

JUnit 4

The scenario you are describing is actually covered in SPR-15927.

It is impossible to have a custom TestRule injected by Spring actually picked up as a rule by JUnit if Spring is also configured via rules (e.g., via SpringClassRule and SpringMethodRule).

The custom TestRule field will in fact be injected by Spring, but that's too late in the game.

In other words, by the time the Spring rules are used to perform dependency injection, the current Runner will not notice that the injected custom TestRule exists, since the field was previously null during the rule detection phase.

It's basically a "chicken and egg" problem, and there is no built-in workaround for JUnit 4.

However, you can achieve something similar by asking Spring to perform dependency injection on an existing rule, but that requires custom code. See SPR-10252 for details.

JUnit Jupiter (JUnit 5)

With JUnit Jupiter 5.1 this should actually be easier to accomplish. Namely, you can combine parameterized test support with Spring without any problems.

The trick with JUnit Jupiter is to make sure you register the SpringExtension at the class level (e.g., via @ExtendWith, @SpringJUnitConfig, or similar). Then you can use @RegisterExtension and @Autowired on a field to have a Spring-managed extension injected into the test instance and used by JUnit Jupiter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!