Skip to content

Latest commit

 

History

History
61 lines (40 loc) · 2.45 KB

http-client_testing.md

File metadata and controls

61 lines (40 loc) · 2.45 KB

Required dependencies: io.ktor:%artifact_name%

Ktor provides a MockEngine that simulates HTTP calls without connecting to the endpoint.

Ktor provides a MockEngine that simulates HTTP calls without connecting to the endpoint.

Add dependencies {id="add_dependencies"}

Before using MockEngine, you need to include the %artifact_name% artifact in the build script.

Usage {id="usage"}

Share client configuration {id="share-config"}

Let's see how to use MockEngine to test a client. Suppose the client has the following configuration:

  • The CIO engine is used to make requests.
  • The Json plugin is installed to deserialize incoming JSON data.

To test this client, its configuration needs to be shared with a test client, which uses MockEngine. To share a configuration, you can create a client wrapper class that takes an engine as a constructor parameter and contains a client configuration.

{src="snippets/client-testing-mock/src/main/kotlin/com/example/Application.kt" include-lines="13-15,24-32"}

Then, you can use the ApiClient as follows to create an HTTP client with the CIO engine and make a request.

{src="snippets/client-testing-mock/src/main/kotlin/com/example/Application.kt" include-lines="16-22"}

Test a client {id="test-client"}

To test a client, you need to create a MockEngine instance with a handler that can check request parameters and respond with the required content (a JSON object in our case).

{src="snippets/client-testing-mock/src/test/kotlin/ApplicationTest.kt" include-lines="14-20"}

Then, you can pass the created MockEngine to initialize ApiClient and make required assertions.

{src="snippets/client-testing-mock/src/test/kotlin/ApplicationTest.kt" include-lines="10-26"}

You can find the full example here: client-testing-mock.