最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Load the port into @ConfigurationProperties data class in SpringBootTest with random port - Stack Overflow

programmeradmin2浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论