https://kotlinlang.org logo
#ktor
Title
# ktor
p

Philipp Mayer

06/10/2020, 12:38 PM
Hello guys, I need some help regarding the usage of the application.conf file. I have a service which reads his configuration from application.conf:
Copy code
class MqttHandler : SensorExchangeUseCase {
    /**
     *  Factory to read the application.conf file
     *  <https://stackoverflow.com/questions/53891189/how-do-i-use-custom-configuration-in-ktor>
     */
    private val config: MqttConfig = with(ConfigFactory.load()) {
        MqttConfig(
            this.getString("mqtt.topic"),
            getString("mqtt.brokerUrl"),
            getInt("mqtt.port"),
            getString("mqtt.clientId")
        )
    }
To test that, I created the following test:
Copy code
class MqttHandlerTest : FunSpec({
    withTestApplication {
        (environment.config as MapApplicationConfig).apply {
            put("mqtt.topic", "karlheinz")
            put("mqtt.brokerUrl", container.host)
            put("mqtt.port", port.toString())
            put("mqtt.clientId", "Karl")
        }
        main()
    }


    test("should read correct Config from HOCON File") {
        with(ConfigFactory.load()) {
            getString("mqtt.topic") shouldBe "karlheinz"
            getString("mqtt.brokerUrl") shouldBe container.host
            getInt("mqtt.port") shouldBe port
            getString("mqtt.clientId") shouldBe "Karl"
        }
    }
However, my test fails since it loads the values which are in my local file and not the values that I put there with
withTestApplication
. My Service is not an application module. How could I test the behaviour? It feels like I'm missing something. Thanks in advance!
One thing that came to my mind was making the ConfigObject a property in the constructor. That would be way cleaner and easier to test. I guess I'll go with that.
m

mp

06/10/2020, 3:02 PM
ktor's config stuff is overcomplicated and unnecessary, IMO. I'd skip it and do config with tools of your choosing in a way that fits more naturally with your project's structure.
There are lots of ways to do config. I maintain a demo project for ktor that shows one viable approach: https://bitbucket.org/marshallpierce/ktor-demo/src/20f37b87fb24ed62043da96e35fae792d6f39177/src/main/kotlin/org/mpierce/ktordemo/KtorDemo.kt#lines-62
but no matter what you pick, there's no reason why your http server lib needs to dictate how you configure the rest of your app.