Hello,
It seems org.springframework.test.web.reactive.server.WebTestClient never send my body in a post http request. I currently use springboot 2.2.0.RELEASE (Spring Test 5.2.0.RELEASE). I did the following :
@Component
class UserHandler(private val userRepo: UserRepository) {
suspend fun addUser(req: ServerRequest): ServerResponse = coroutineScope {
val log: Logger = LoggerFactory.getLogger(UserHandler::class.java)
log.info("TEST TEST TEST: {}", req.awaitBody()) // Here to log the body
val userCreated: Deferred<User> = async { userRepo.save(req.awaitBody()) }
ServerResponse.ok().json().bodyValueAndAwait(userCreated.await())
}
}
@Configuration
class RouterConfig {
companion object {
const val USER_ID_PATH_PARAM = "id"
}
@Bean
fun userRoutes(userHandler: UserHandler) = coRouter {
User.USER_API_ENDPOINT.and(accept(MediaType.APPLICATION_JSON)).nest {
POST(Strings.EMPTY, userHandler::addUser)
}
}
}
@WebFluxTest
@ContextConfiguration(classes = [RouterConfig::class, UserHandler::class])
class UserHandlerTests(@Autowired private val webClient: WebTestClient) {
@MockBean
private lateinit var userRepository: UserRepository
@Test
fun addCorrectUser() {
val user1: User = User(1L, "boby@bob.bb")
webClient.post().uri(User.USER_API_ENDPOINT).bodyValue(user1).exchange()
.expectBody().json("{\"toto\": \"toto\"}") // What ever the result
}
}
Then I can see in test logs, the body sent with the request :
java.lang.AssertionError:
Expected: toto
but none found
> POST /user
> WebTestClient-Request-Id: [5]
> Content-Type: [application/json]
> Content-Length: [47]
{"id":1,"email":"boby@bob.bb","birthDate":null}
< 500 INTERNAL_SERVER_ERROR Internal Server Error
< Content-Type: [application/json]
< Content-Length: [17704]
But in my UserHandler logs it seems the body is empty :
2019-11-20 11:31:29.549 INFO 1660 --- [er @coroutine#9] c.l.o.cash.demo.user.UserHandler : TEST TEST TEST: {}
It works if I started my apps, this issue only occurs with WebTestClient. I suspect the log is wrong, I read the exchange method definition : "Perform the exchange without a request body." but I didn't find other method to do the job. It seems anyway the exchange method takes care about the body :
public Mono<ClientResponse> exchange() {
ClientRequest request = (this.inserter != null ?
initRequestBuilder().body(this.inserter).build() :
initRequestBuilder().build());
...
Do you have any guess ? Thank you !
Comment From: kizux
Sorry, wrong issue, my log part in UserHandler is wrong ! Just realized few seconds after created the issue