Hi everyone! I’ve created a test project with Spri...
# ktor
l
Hi everyone! I’ve created a test project with Spring Boot + Ktor Client and wanted to know how to mock Ktor Client responses. This is my setup:
Copy code
@SpringBootApplication
class TodoConsumerApplication {
    @Bean
    fun httpClient() = HttpClient {
        install(JsonFeature)
    }
}

fun main(args: Array<String>) {
    runApplication<TodoConsumerApplication>(*args)
}
Copy code
@Service
class TodoConsumerService(
    private val httpClient: HttpClient
) {
    suspend fun getItemsTwoTimes() {
        val result1 = httpClient.get<String>("<http://localhost:8080/items>")
        val result2 = httpClient.get<String>("<http://localhost:8080/items>")

        println("Result 1 = $result1 and Result 2 = $result2")
    }
}
Copy code
@ExtendWith(SpringExtension::class)
@SpringBootTest
internal class TodoConsumerServiceTest {
    @MockkBean
    private lateinit var httpClient: HttpClient

    @Autowired
    private lateinit var todoConsumerService: TodoConsumerService

    @Test
    fun getItemsTwoTimes() = runBlocking {

    }
}
I want to mock two different responses in the service using MockEngine
a
Is it possible to provide a different
HttpClient
object in
TodoConsumerServiceTest
?
m
You could've used WireMock, TestServer or similar approach to mock the responses. Slightly less convenient then say Spring's mock server, but not too complicated - and you're completely independent in the choice of your clients.
A small word of warning re. the use of
@MockBean
that you seem to aim for - this creates a new Spring context for every test. Spring contexts aren't very cheap to start, 10 secs to 30 secs is a norm. Might quickly become an issue with more than a handful of tests for your CI duration. Just saying.
a
I mean if you can replace a real client with a different
HttpClient
object, that will use the
MockEngine
, in the
TodoConsumerService
for your test, then you could mock responses.
l
Hi @Aleksei Tirman [JB], I’m not really sure on how to do that with DI