I’m trying to migrate to ktor 2.0 and I’m facing a...
# ktor
k
I’m trying to migrate to ktor 2.0 and I’m facing an issue with tests. Currently I’m using
withTestApplication
where I call
Application.module
function with some arguments like that:
Copy code
withTestApplication({
    module(appModule = appModule)
}) { ... }
now we are suppose to use
testApplication
function that seemingly calls
Application.module
function automatically, so passing custom arguments seems not possible anymore and it makes testing much more difficult. Is there any way to call
Application.module
manually? Is there any workaround?
p
You should be able to something like
Copy code
testApplication {
  application {
    module(appModule = appModule)
  }
  // ... test using `client` or `createClient { ... }`
}
h
testApplication
picks up
application.conf
and will automatically load modules there (e.g.
Application.module
. If you want a different set of modules all together, you can modify `environment`: https://ktor.io/docs/testing.html#add-modules
k
Thanks Phil, but when I do that my
Application.module
gets called twice, so my plugins gets installed twice and it results in exception
@hruan it seems like it’s the information I was missing. Thanks!
p
try
Copy code
testApplication {
            environment {
                modules.clear()
                modules.add(appModule)
            }
}
👍 1
r
testApplication
should have a
useApplicationConf: Boolean = true
parameter or something like that to let you disable this behavior. Maybe I want an
application.conf
file in my main source set and maybe I don’t want to use it in my tests
p
you can override the config to load (either by file or from map, etc) in the
environment
block: https://ktor.io/docs/testing.html#environment
r
Isn’t that after the fact? In your code just above you removed modules from an existing collection, means they’re already loaded from the config file, doesn’t it?
p
It may well be the code I provided doesn’t work - I’ve not used the HOCON/config based Ktor approach - I tend to use an embeddedServer. Hence “try” 😉 but you’re right - it might be better to remove/change/override the config.
r
Well I just thought everything inside the
testApplication
block happened after the config had been read but maybe it’s not the case
p
My understanding is, the
testApplication
block doesn’t action the configuration until the first client request is made (and the test engine is started)
👍 1
k
Using approach with custom
.conf
file in
test/resource
folder, mentioned here worked well. I’ve left
modules
empty and no modules are loaded:
Copy code
// test/resource/application-test.conf
ktor {
    application {
        modules = [ ]
    }
}


@Test
fun test() = testApplication {
    environment {
        config = ApplicationConfig("application-test.conf")
    }
}