Search code examples
kotlinktorhoverfly

Hoverfly Ktor client Apache Kotlin


I tried to do unit test with Hoverfly to mock external API.

companion object {
    @ClassRule @JvmField
    val hoverflyRule: HoverflyRule = HoverflyRule.inSimulationMode(dsl(
            service("people.zoho.com")
                    .get("/people/api/forms/P_EmployeeView/records").queryParam("authtoken","TOKEN")
                        .willReturn(success("{test:test}", "application/json"))
    ))
}

When I use the Apache client with ktor, that doesn't work. But with another client like khttp, it works. Any ideas why?


Solution

  • You should setup default system proxy in Apache config: http://hoverfly.readthedocs.io/projects/hoverfly-java/en/latest/pages/misc/misc.html

    example with ktor(0.9.3-alpha-3):

    class ApplicationMockupTest {
      companion object {
        @ClassRule
        @JvmField
        val hoverflyRule: HoverflyRule = HoverflyRule.inSimulationMode(
            dsl(
                service("people.zoho.com:443")
                    .get("/people/api/forms/P_EmployeeView/records")
                    .queryParam("authtoken", "TOKEN")
                    .willReturn(success("{j:gr}", "application/json"))
            )
        )
      }
    
      @Test
      fun exampleTest() = runBlocking<Unit> {
        val client = HttpClient(Apache.setupDefaultProxy())
        val token = "TOKEN"
        val url = "https://people.zoho.com/people/api/forms/P_EmployeeView/records?authtoken=$token"
        val requestString = client.get<String>(url)
        hoverflyRule.verifyAll()
        Unit
      }
    
      fun HttpClientEngineFactory<ApacheEngineConfig>.setupDefaultProxy() = config {
        customizeClient {
            useSystemProperties()
        }
      }
    }