Eduards Sizovs opened SPR-10252 and commented
In some situations it's convenient to inject dependencies into JUnit's @Rule
and @ClassRule
managed class' instances. Currently it can be achieved by extending DependencyInjectionTestExecutionListener
(DITEL) with additional logic that looks for @Rule
and @ClassRule
fields and autowires them the same way as test instance is autowired. Even given the opportunity to extend class, I consider this functionality common enough.
Affects: 3.2.1
Issue Links: - #20481 Autowired Rules do not work with SpringClassRule or SpringMethodRule
5 votes, 6 watchers
Comment From: spring-projects-issues
Ken Wang commented
This feature would be really nice to have. Especially since Rules are instantiated before the test beans are autowired, one cannot even supply the dependencies in the Rule constructors.
Comment From: spring-projects-issues
Sam Brannen commented
FWIW, if you are using the SpringJUnit4ClassRunner
(or SpringRunner
) you can actually already inject dependencies into @Rule
instances if you register the rule as a bean in the application context and annotate the field in the test class with @Autowired
in addition to @Rule
.
That's a trick I've seen used in various projects.
Comment From: spring-projects-issues
Ken Wang commented
Interesting, I'll give that a try. Do you think @Configurable
would work as well?
Comment From: spring-projects-issues
Sam Brannen commented
Do you think
@Configurable
would work as well?
To be honest, I haven't put much thought into that as an option, and I can imagine that there might be a timing issue there.
So, if you'd be willing to give it a shot and report back here on your findings, that would be greatly appreciated! ;-)
Comment From: spring-projects-issues
Ken Wang commented
My my testing, it does not.
Comment From: spring-projects-issues
Sam Brannen commented
Please note that this issue is related to #20481 and this answer on Stack Overflow.
Comment From: kenwang-okta
Any chance of this ever happening?
Comment From: eschulma
I would love to know how this could work for @ClassRule
.
Comment From: sbrannen
I would love to know how this could work for
@ClassRule
.
I've not implemented it, but in theory it should work the same as the code in DependencyInjectionTestExecutionListener.injectDependencies()
except that the bean
would be the value of the @ClassRule
field.
Comment From: sbrannen
Since the community has not displayed much interest in this feature over the years, I am closing this issue.
However, if you are using JUnit Jupiter instead of JUnit 4, please note that JUnit Jupiter extensions can access the ApplicationContext
via SpringExtension.getApplicationContext(...)
and directly retrieve the beans they need.