The Kotlin way of doing this is to use a companion object (caveat: I have not actually tried this)
companion object PropertiesSource {
@DynamicPropertySource
fun properties(registry: DynamicPropertyRegistry) {
registry.add("testApi.baseUrl",
{"http://localhost:" + mockWebServer.port})
}
}
UPDATE
Here is a working example that sets up the MockWebServer in a Kotlin SpringBootTest
package com.example.gradlebitch
import mu.KotlinLogging
import okhttp3.mockwebserver.MockWebServer
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.DynamicPropertyRegistry
import org.springframework.test.context.DynamicPropertySource
import reactor.core.publisher.Mono
import java.io.IOException
import java.time.temporal.ChronoUnit
import java.util.*
@SpringBootTest
class KotlinMockWebServerTest {
companion object MockWebServerSetup {
private val log = KotlinLogging.logger {}
private val tenSec: java.time.Duration = java.time.Duration.of(10, ChronoUnit.SECONDS)
private var untouchableMockWebServer: MockWebServer? = null // go through the mono, please
private var webServerMono: Mono<MockWebServer> = Mono.fromCallable {
Optional.ofNullable<MockWebServer>(untouchableMockWebServer)
.orElseGet {
try {
log.warn("Starting Up Midpoint MockServer")
untouchableMockWebServer = MockWebServer()
untouchableMockWebServer!!.start()
log.warn(
"Midpoint MockServer running at: "
+ untouchableMockWebServer!!.url("")
)
return@orElseGet untouchableMockWebServer
} catch (e: IOException) {
throw RuntimeException(e)
}
}
}
@JvmStatic
@DynamicPropertySource
fun testProperties(registry: DynamicPropertyRegistry) {
log.warn("Setting provision.midpoint.uri to be dynamic")
registry.add("provision.midpoint.uri") { mockUrl }
}
private val mockUrl: String
get() = webServerMono.block(tenSec)?.url("").toString()
@JvmStatic
@BeforeAll
@Throws(IOException::class)
fun setUp() {
log.warn("Waiting for MockWebServer")
webServerMono.block(tenSec)
}
@JvmStatic
@AfterAll
@Throws(IOException::class)
fun shutDownMockWebServer() {
log.warn("Shutting Down MockWebServer at $mockUrl")
webServerMono.block(tenSec)?.shutdown()
untouchableMockWebServer = null
}
}
@Test
public fun testSomething() {
log.warn("Mock Url: $mockUrl")
}
}