I have changed some unit tests from the `lateinit ...
# spring
r
I have changed some unit tests from the
lateinit var
way to the
@Autowired val
constructor way (junit5). one test class with 4 test method can now only execute 1 test method successfully. the other ones are failing with
No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' available
. What makes this test class different, is a
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
annotation. I am also running with
junit.jupiter.testinstance.lifecycle.default=per_class
. Maybe all of this doesn’t play nice together?
s
Constructor injection for Spring-managed components can never work with
@DirtiesContext
before or after test methods.
The reason is that the test instance will retain references to beans that came from a closed
ApplicationContext
, and DI will not occur again (to reset the references) since the constructor will only be invoked once.
To use
@DirtiesContext
before or after methods, one must allow dependencies from Spring to be injected via fields or setter/configuration methods.
(Response from Sam Brannen)
r
thanks for the answer. so in other words the problem is, that the constructor is only called once but - when using setter injection - it will call the setters in between the tests with fresh beans