Skip to content

Commit 7884aba

Browse files
committed
Add bodyNotNull for RestClient Kotlin extensions
1 parent 3002813 commit 7884aba

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

Diff for: spring-web/src/main/kotlin/org/springframework/web/client/RestClientExtensions.kt

+7-1
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,12 @@ inline fun <reified T : Any> RestClient.RequestBodySpec.bodyWithType(body: T): R
4242
inline fun <reified T : Any> RestClient.ResponseSpec.body(): T? =
4343
body(object : ParameterizedTypeReference<T>() {})
4444

45+
/**
46+
* Extension for [RestClient.ResponseSpec.body] providing a `bodyNotNull<Foo>()` variant
47+
* To leverage Kotlin null safety, this extension throws a [NoSuchElementException] if the response body is null.
48+
*/
49+
inline fun <reified T : Any> RestClient.ResponseSpec.bodyNotNull(): T =
50+
body(object : ParameterizedTypeReference<T>() {}) ?: throw NoSuchElementException("Response body is null when a non-null type was expected.")
4551

4652
/**
4753
* Extension for [RestClient.ResponseSpec.toEntity] providing a `toEntity<Foo>()` variant
@@ -52,4 +58,4 @@ inline fun <reified T : Any> RestClient.ResponseSpec.body(): T? =
5258
* @since 6.1
5359
*/
5460
inline fun <reified T : Any> RestClient.ResponseSpec.toEntity(): ResponseEntity<T> =
55-
toEntity(object : ParameterizedTypeReference<T>() {})
61+
toEntity(object : ParameterizedTypeReference<T>() {})

Diff for: spring-web/src/test/kotlin/org/springframework/web/client/RestClientExtensionsTests.kt

+14
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,11 @@
1616

1717
package org.springframework.web.client
1818

19+
import io.mockk.every
1920
import io.mockk.mockk
2021
import io.mockk.verify
2122
import org.junit.jupiter.api.Test
23+
import org.junit.jupiter.api.assertThrows
2224
import org.springframework.core.ParameterizedTypeReference
2325

2426
/**
@@ -45,6 +47,18 @@ class RestClientExtensionsTests {
4547
verify { responseSpec.body(object : ParameterizedTypeReference<List<Foo>>() {}) }
4648
}
4749

50+
@Test
51+
fun `ResponseSpec#bodyNotNull with reified type parameters`() {
52+
responseSpec.bodyNotNull<List<Foo>>()
53+
verify { responseSpec.body(object : ParameterizedTypeReference<List<Foo>>() {}) }
54+
}
55+
56+
@Test
57+
fun `ResponseSpec#bodyNotNull with null response throws NoSuchElementException`() {
58+
every { responseSpec.body(any<ParameterizedTypeReference<Foo>>()) } returns null
59+
assertThrows<NoSuchElementException> { responseSpec.bodyNotNull<Foo>() }
60+
}
61+
4862
@Test
4963
fun `ResponseSpec#toEntity with reified type parameters`() {
5064
responseSpec.toEntity<List<Foo>>()

0 commit comments

Comments
 (0)