MockRestServiceServer: how to mock a POST call with a body?

16,427

You can use content().string to verify body:

.andExpect(content().string(expectedContent))

Or content().bytes:

this.mockServer.expect(content().bytes("foo".getBytes()))

this.mockServer.expect(content().string("foo"))

Share:
16,427
Sasha Shpota
Author by

Sasha Shpota

I love building applications with Java, Go, Kotlin, JS/TS, Docker, and Kubernetes. I believe modern engineers must learn fast, switch technologies when needed and develop their expertise in different areas. Find me on my: ( Blog | Twitter | GitHub )

Updated on July 12, 2022

Comments

  • Sasha Shpota
    Sasha Shpota almost 2 years

    I am trying to mock a POST method with MockRestServiceServer in the following way:

    MockRestServiceServer server = bindTo(restTemplate).build();
    server.expect(requestTo("/my-api"))
            .andExpect(method(POST))
            .andRespond(withSuccess(expectedResponce, APPLICATION_JSON));
    

    Problem: How do I verify a request body in this setup?

    I browsed through the documentation and some examples and still can't figure out how it can be done.

    • Igor Khvostenkov
      Igor Khvostenkov over 4 years
      Why do you want to check the request body? This is input data, which should not be verified. Is it just typo and you meant response body?
    • Sasha Shpota
      Sasha Shpota over 4 years
      @IgorKhvostenkov it is a POST requests which means it sends a piece of data. I want to verify that the information that is sent is correct.
    • stacker
      stacker over 4 years
      I don't think you are doing it right, if you are trying to verify request body, you only need to test how you create the body, not mocking the Api and test what was sent by you there...
    • Igor Khvostenkov
      Igor Khvostenkov over 4 years
      This really does not matter if this is GET or POST. Conceptually, this is strange to test something which you manually define as correct or as wrong, but is not decided by production code. You can use approach @user7294900 has proposed, but more as narrowing the scope of your mock or having a more precise trigger, but not as verification of your production code.
    • Sasha Shpota
      Sasha Shpota over 4 years
      @IgorKhvostenkov maybe "verify" is not the best word here. Let me elaborate. I am writing an integration test. I do not want to hit a real API from the test, instead I am mocking the API. But if I do not check a request body the mocked API will return a successful response for all requests which is something I don't want.
    • Igor Khvostenkov
      Igor Khvostenkov over 4 years
      Ok, I've got your idea, posted example how I would do this.