I have a Kotlin spring boot test running on a random port.
Also I have an application-test.yml file where all the properties are set.
Inside that file I have one property which holds a URL to my own server (smth.like: localhost:{local_port}
). Inside the code I using @ConfigurationProperties
data class to load the properties. The question is how to set the port to that url when test runs (before the test method called but after test Context is initialized)?
My test class:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class MySpringBootTest {
@LocalServerPort
var port: Int = 0
@Autowired
private lateinit var myService: MyService
@Test
fun testProductionMethod() {
val result = myService.doSomething()
println("Result: $result")
}
}
My application-test.yml:
my:
custom:
url: http://localhost:{local_port}
My Configuration data class (which is injected into MyService
later):
@ConfigurationProperties(prefix = "my.custom")
data class MyCustomProperties(
val url: String = "" // Should be set dynamically
)
Service which uses the properties:
@Service
class MyService(private val properties: MyCustomProperties) {
fun reqeust() {
val url = properties.url
// request to url...
}
}
Already tried to set it with with @BeforeEach
, ApplicationContextInitializer
, @DynamicPropertySource
and @TestPropertySource
, didn't work.
Please do not answer with AI generated texts.