Skip to content

Commit

Permalink
Add a requiredBody() extension to RestClient.ResponseSpec
Browse files Browse the repository at this point in the history
Closes gh-32703
  • Loading branch information
Donghh0221 authored and sdeleuze committed Apr 26, 2024
1 parent 3002813 commit a662f5e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -42,6 +42,14 @@ 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 with a non-nullable
* return value.
* @throws NoSuchElementException if there is no response body
* @since 6.2
*/
inline fun <reified T : Any> RestClient.ResponseSpec.requiredBody(): T =
body(object : ParameterizedTypeReference<T>() {}) ?: throw NoSuchElementException("Response body is required")

/**
* Extension for [RestClient.ResponseSpec.toEntity] providing a `toEntity<Foo>()` variant
Expand All @@ -52,4 +60,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>() {})
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -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

0 comments on commit a662f5e

Please sign in to comment.