https://kotlinlang.org logo
#http4k
Title
# http4k
d

DanielZ

04/01/2022, 9:26 AM
Hi, I have some difficulties with
Environment
in following example the second test fails:
Copy code
import com.github.stefanbirkner.systemlambda.SystemLambda
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.http4k.cloudnative.env.Environment
import org.http4k.cloudnative.env.EnvironmentKey
import org.http4k.cloudnative.env.Port
import org.http4k.lens.string
import org.junit.jupiter.api.Test

private val developmentPort = Port(9999)
private val defaultPort = Port(8080)

private const val developmentProfile = "development"
private const val SPRING_PROFILE_ACTIVE = "SPRING_PROFILE_ACTIVE"

private val springProfileLens = EnvironmentKey.string().defaulted(SPRING_PROFILE_ACTIVE, "")

class ConfigurationTest {
    @Test
    fun configuration1() {
        assertThat(Configuration.serverPort, equalTo(defaultPort))
    }

    @Test
    fun configuration2() {
        SystemLambda.withEnvironmentVariable(SPRING_PROFILE_ACTIVE, developmentProfile).execute {
            assertThat(Configuration.serverPort, equalTo(developmentPort))
        }
    }

    @Test
    fun configuration3() {
        assertThat(Configuration.serverPort, equalTo(defaultPort))
    }
}


object Configuration {
    val serverPort: Port
        get() {
            println("selected profile: ${springProfileLens(environment)}")
            println("selected profile (env): ${System.getenv(SPRING_PROFILE_ACTIVE).orEmpty()}")
            return when (springProfileLens(environment)) {
                developmentProfile -> developmentPort
                else -> defaultPort
            }
        }

    private val environment: Environment
        get() = Environment.ENV overrides Environment.JVM_PROPERTIES
}
For some reasons I don’t understand I receive following output:
Copy code
selected profile: 
selected profile (env): development
I expected my
springProfileLens(environment)
would return
development
but it’s not. Do you have an idea where I’m wrong? Thanks a lot
Oh, I see
Environment.ENV
is only evaluated once, since it is in companion object with a direct initialization. Is there an easy way to test configurations which are depending on environment variables using
Environment
?
j

James Richardson

04/01/2022, 8:50 PM
You could define a method that returns the environment maybe, and just use that in your companion object? Then you can test the method, not the companion object
👍 1
31 Views