2

I'm writing some tests for a Spring WebFlux application and I'm trying to mock a scenario where a request doesn't have a body. I reached for the built-in MockServerRequest, figuring I'd use the built-in mock over making my own. It does allow constructing an instance without a body, but my tests are failing as all of its methods for extracting the body contain an assertion that the body is not null. This doesn't seem to line up with how an actual request would behave. It's totally possible to make a request with no body. I'd also say it's reasonable to have code that checks to see if there's a body, as backed up by the existence of methods like awaitBodyOrNull (I'm using Kotlin).

Am I missing/misunderstanding something here? I'm constructing my mock by just doing MockServerRequest.builder().build() (the methods under test don't care about anything other than the body). Is this class perhaps not actually meant to be used on its own? I'm not finding anyone else asking about this so I feel like I must be overlooking something.

For now I'll work around this by just making my own mock.

Stephen Cohen
  • 370
  • 1
  • 2
  • 12
  • I didn't read too closely what's going on but Flux/Reactor doesn't all nulls in the stream. You will have to submit a Mono.empty(). So, whatever you're mocking should never return a null in the body, and in fact it won't be able to because the stream will abort any time it is attempted. – K.Nicholas Aug 21 '20 at 19:13
  • I edited the title to be a bit clearer. I'm not trying to pass null to the mock builder, I'm just trying to mock a request for which no body was sent. Returning `Mono.empty()` (which would then get translated into `null` for Kotlin) is the behavior I would expect. Instead `mockRequest.awaitBodyOrNull()` is throwing an `IllegalStateException`, rather than returning null. – Stephen Cohen Aug 21 '20 at 19:22
  • Oh, wait, there it is. Looking at the source code a bit more closely, it's expecting the body you give it to already be wrapped in a `Mono`. I assumed from the parameter being type `Object` that it would wrap the body (or the lack thereof) for me. If you want to format that as an answer, I'll give you credit. Otherwise I'll just close the question myself. – Stephen Cohen Aug 21 '20 at 19:28
  • Naw, no worries, glad you got it sorted out. – K.Nicholas Aug 21 '20 at 19:29
  • Alrighty then. Thanks for the mental push. :) – Stephen Cohen Aug 21 '20 at 19:30

1 Answers1

4

MockServerRequest.Builder expects you to give it a body already wrapped in a Mono. It doesn't do any wrapping for you. So mocking an empty request is done with MockServerRequest.builder().body(Mono.empty<TestDto>()).

Stephen Cohen
  • 370
  • 1
  • 2
  • 12