Skip to content

Commit

Permalink
Add awaitBodyOrNull to WebClient.ResponseSpec
Browse files Browse the repository at this point in the history
Such variant is already provided for ClientResponse but not
for WebClient.ResponseSpec.

Closes spring-projectsgh-26731
  • Loading branch information
ValentinShakhov authored and lxbzmy committed Mar 26, 2022
1 parent f7e1d56 commit 7fe859c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
Expand Up @@ -21,6 +21,7 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.reactive.asFlow
import kotlinx.coroutines.reactive.awaitSingle
import kotlinx.coroutines.reactive.awaitSingle
import kotlinx.coroutines.reactive.awaitSingleOrNull
import kotlinx.coroutines.reactor.asFlux
import kotlinx.coroutines.reactor.mono
import org.reactivestreams.Publisher
Expand Down Expand Up @@ -143,6 +144,17 @@ suspend inline fun <reified T : Any> WebClient.ResponseSpec.awaitBody() : T =
else -> bodyToMono<T>().awaitSingle()
}

/**
* Coroutines variant of [WebClient.ResponseSpec.bodyToMono].
*
* @author Valentin Shakhov
*/
suspend inline fun <reified T : Any> WebClient.ResponseSpec.awaitBodyOrNull() : T? =
when (T::class) {
Unit::class -> awaitBodilessEntity().let { Unit as T? }
else -> bodyToMono<T>().awaitSingleOrNull()
}

/**
* Coroutines variant of [WebClient.ResponseSpec.toBodilessEntity].
*/
Expand Down
Expand Up @@ -136,6 +136,25 @@ class WebClientExtensionsTests {
}
}

@Test
fun awaitBodyOrNull() {
val spec = mockk<WebClient.ResponseSpec>()
every { spec.bodyToMono<String>() } returns Mono.just("foo")
runBlocking {
assertThat(spec.awaitBodyOrNull<String>()).isEqualTo("foo")
}
}

@Test
fun `awaitBodyOrNull of type Unit`() {
val spec = mockk<WebClient.ResponseSpec>()
val entity = mockk<ResponseEntity<Void>>()
every { spec.toBodilessEntity() } returns Mono.just(entity)
runBlocking {
assertThat(spec.awaitBodyOrNull<Unit>()).isEqualTo(Unit)
}
}

@Test
fun awaitBodilessEntity() {
val spec = mockk<WebClient.ResponseSpec>()
Expand Down

0 comments on commit 7fe859c

Please sign in to comment.