Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a requiredBody() extension to RestClient.ResponseSpec #32703

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -42,6 +42,12 @@ inline fun <reified T : Any> RestClient.RequestBodySpec.bodyWithType(body: T): R
inline fun <reified T : Any> RestClient.ResponseSpec.body(): T? =
body(object : ParameterizedTypeReference<T>() {})

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

/**
* Extension for [RestClient.ResponseSpec.toEntity] providing a `toEntity<Foo>()` variant
Expand All @@ -52,4 +58,4 @@ inline fun <reified T : Any> RestClient.ResponseSpec.body(): T? =
* @since 6.1
*/
inline fun <reified T : Any> RestClient.ResponseSpec.toEntity(): ResponseEntity<T> =
toEntity(object : ParameterizedTypeReference<T>() {})
toEntity(object : ParameterizedTypeReference<T>() {})
Expand Up @@ -16,9 +16,11 @@

package org.springframework.web.client

import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.springframework.core.ParameterizedTypeReference

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

@Test
fun `ResponseSpec#requiredBody with reified type parameters`() {
responseSpec.requiredBody<List<Foo>>()
verify { responseSpec.body(object : ParameterizedTypeReference<List<Foo>>() {}) }
}

@Test
fun `ResponseSpec#requiredBody with null response throws NoSuchElementException`() {
every { responseSpec.body(any<ParameterizedTypeReference<Foo>>()) } returns null
assertThrows<NoSuchElementException> { responseSpec.requiredBody<Foo>() }
}

@Test
fun `ResponseSpec#toEntity with reified type parameters`() {
responseSpec.toEntity<List<Foo>>()
Expand Down