File tree 2 files changed +21
-1
lines changed
main/kotlin/org/springframework/web/client
test/kotlin/org/springframework/web/client
2 files changed +21
-1
lines changed Original file line number Diff line number Diff line change @@ -42,6 +42,12 @@ inline fun <reified T : Any> RestClient.RequestBodySpec.bodyWithType(body: T): R
42
42
inline fun <reified T : Any > RestClient.ResponseSpec.body (): T ? =
43
43
body(object : ParameterizedTypeReference <T >() {})
44
44
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." )
45
51
46
52
/* *
47
53
* Extension for [RestClient.ResponseSpec.toEntity] providing a `toEntity<Foo>()` variant
@@ -52,4 +58,4 @@ inline fun <reified T : Any> RestClient.ResponseSpec.body(): T? =
52
58
* @since 6.1
53
59
*/
54
60
inline fun <reified T : Any > RestClient.ResponseSpec.toEntity (): ResponseEntity <T > =
55
- toEntity(object : ParameterizedTypeReference <T >() {})
61
+ toEntity(object : ParameterizedTypeReference <T >() {})
Original file line number Diff line number Diff line change 16
16
17
17
package org.springframework.web.client
18
18
19
+ import io.mockk.every
19
20
import io.mockk.mockk
20
21
import io.mockk.verify
21
22
import org.junit.jupiter.api.Test
23
+ import org.junit.jupiter.api.assertThrows
22
24
import org.springframework.core.ParameterizedTypeReference
23
25
24
26
/* *
@@ -45,6 +47,18 @@ class RestClientExtensionsTests {
45
47
verify { responseSpec.body(object : ParameterizedTypeReference <List <Foo >>() {}) }
46
48
}
47
49
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
+
48
62
@Test
49
63
fun `ResponseSpec#toEntity with reified type parameters` () {
50
64
responseSpec.toEntity<List <Foo >>()
You can’t perform that action at this time.
0 commit comments