【问题标题】:How to provide an HttpClient to ktor server from the outside to facilitate mocking external services?如何从外部向 ktor 服务器提供 HttpClient 以方便 mock 外部服务?
【发布时间】:2022-10-24 17:32:37
【问题描述】:

我正在尝试从外部向我的 ktor 服务器提供HttpClient,以便我可以模拟external services 并编写测试,但是当我运行测试时出现此异常:

Please make sure that you use unique name for the plugin and don't install it twice. Conflicting application plugin is already installed with the same key as `Compression`
io.ktor.server.application.DuplicatePluginException: Please make sure that you use unique name for the plugin and don't install it twice. Conflicting application plugin is already installed with the same key as `Compression`
    at app//io.ktor.server.application.ApplicationPluginKt.install(ApplicationPlugin.kt:112)
    at app//com.example.plugins.HTTPKt.configureHTTP(HTTP.kt:13)
    at app//com.example.ApplicationKt.module(Application.kt:14)
    at app//com.example.ApplicationTest$expected to work$1$1.invoke(ApplicationTest.kt:39)
    at app//com.example.ApplicationTest$expected to work$1$1.invoke(ApplicationTest.kt:38)

这对我来说有点出乎意料,因为据我所知,我没有两次应用Compression 插件。如果我正常运行服务器并使用curl 手动调用我的端点,那么它会按预期工作。我究竟做错了什么?

我添加了一个可运行的示例项目here with a failing test

【问题讨论】:

    标签: kotlin ktor ktor-client


    【解决方案1】:

    问题是您有application.conf 文件,默认情况下,testApplication 函数会尝试加载在那里枚举的模块。由于您还在 application {} 块中显式加载它们,因此会出现 DuplicatePluginException。要解决您的问题,您可以显式加载一个空配置而不是默认配置:

    // ...
    application {
        module(client)
    }
    
    environment {
        config = MapApplicationConfig()
    }
    // ...
    

    【讨论】:

      猜你喜欢
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 2015-04-18
      • 2014-08-25
      • 2016-10-07
      • 1970-01-01
      相关资源
      最近更新 更多