Member-only story
Mocking Spring’s reactive WebClient in Kotlin, using MockK for UnitTests
1 min readJan 24, 2022
This is purely a quick Note To Self, so that I can find it again, when googling for it 🤓
Let’s assume we want to test a method, invoking a WebClient call in a Unit Test (no Integration Test). Example:
private fun loadSomething(id: String): SomeThing {
return runBlocking(Dispatchers.IO) {
webClient
.get()
.uri("/someurl/{id}", id)
.exchangeToMono { response ->
if (response.statusCode() == HttpStatus.OK) {
response.bodyToMono<SomeThing>()
} else {
throw HttpClientErrorException.create(
HttpStatus.UNPROCESSABLE_ENTITY,
"No SomeThing found for id $id",
HttpHeaders(),
"".toByteArray(),
Charsets.UTF_8
)
}
}
.timeout(Duration.ofSeconds(TIMEOUT))
.retry(MAX_RETRIES)
.block()!!
}
}
It might look cumbersome to create a mock for this. Usually, when using Java, this is very true. With Kotlin and MockK, however, things are definitely easier, once you found the right matchers.
There might be other ways to achieve this, but this worked for me for now:
val someThing = SomeThing()
every {
webClient.get().uri(any(), any<VarargMatcher<Any>>())
.exchangeToMono<SomeThing>(any())
.timeout(any())
.retry(any())
.block()!!
} returns someThing