I'm currently trying to set up a JUnit 5 test in Kotlin using Spring Boot and a custom test extension for a fake authentication service. The test extension is meant to set up and tear down the test environment for the authentication service, but I'm having issues with dependency injection.
Here's my test setup:
@ExtendWith(FakeAuthService::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = ["spring.cloud.gcp.secretmanager.enabled=false"])
@TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL)
class MyTest {
// ...
}
And here's my FakeAuthService class:
@Component
class FakeAuthService : BeforeEachCallback, AfterEachCallback {
@Value("\${userendpoint.url}")
private lateinit var url: String
override fun beforeEach(context: ExtensionContext?) {
// set up the test environment
// ...
}
override fun afterEach(context: ExtensionContext?) {
// tear down the test environment
// ...
}
}
The issue I'm facing is that dependency injection is not working properly in FakeAuthService, and I'm getting an UninitializedPropertyAccessException when trying to access the url property.
Can anyone help me understand how to properly use a custom test extension with dependency injection in JUnit 5 with Kotlin and Spring Boot?
Thanks in advance!
Programatically regeristering the extension instead seems to work (I guess since spring has already injected the values by then)
So:
@RegisterExtension
@Autowired
private lateinit var fakeAuthService: FakeAuthService
and not:
@ExtendWith(FakeAuthService::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class MyTest {