1

When trying to test Client class, POST call stubbing works correctly, while GET isn't. What I'm doing wrong here / not understanding correctly?

Client code (POST):

HttpResponse httpResponse = new DefaultHttpRequestBuilder(HttpMethod.POST, SERVICE_URL_GET_MAGIC)
                .withBody(parseMagic(magicName))
                .execute();

With stubbing (POST):

stubFor(post(urlEqualTo("/api/get-magic"))
        .withRequestBody(equalToJson(magicNameParsed))
        .willReturn(aResponse()
                .withHeader("Content-Type", "application/json")
                .withBody(magicDtoParsed)));

Works correctly (httpResponse will have 200 OK).

When GET use, it won't stub the api call (httpResponse will be 404 Not found).

HttpResponse httpResponse = new DefaultHttpRequestBuilder(HttpMethod.GET, SERVICE_URL_GET_MAGIC)
                    .withBody(parseMagic(magicName))
                    .execute();

stubFor(get(urlEqualTo("/api/get-magic"))
        .withRequestBody(equalToJson(magicNameParsed))
        .willReturn(aResponse()
                .withHeader("Content-Type", "application/json")
                .withBody(magicDtoParsed)));
Johnny
  • 10,849
  • 11
  • 61
  • 105

1 Answers1

1

I think the problem is that you're expecting a 'body' in your get request, but get requests cannot have a body (only PUT and POST requests can have a body).

try doing the following

stubFor(get(urlEqualTo("/api/get-magic"))
        .willReturn(aResponse()
                .withHeader("Content-Type", "application/json")
                .withBody(magicDtoParsed)));

Note that I've removed the line .withRequestBody(equalToJson(magicNameParsed))

By the way. Stabbing is when you use a knife or sharp object to hurt someone/something. Stubbing is the word you want to use when talking in the context testing :)

Augusto
  • 26,525
  • 5
  • 52
  • 82
  • Sorry about the stAbbing, it showed me auto-correction and I'm just followed it :) will edit it. Regarding the body in GET request, I thought about it, and eventually found out that it's *ok* http://stackoverflow.com/questions/978061/http-get-with-request-body and, my client *do* expect it. – Johnny Aug 16 '15 at 14:13
  • 1
    Wow, didn't know it was allowed... but as people mentioned there it's a bad idea and will eventually be mentioned that this is not allowed. My suggestion would be: do it right, and remove the need to have a body. Personally, from the few hundred APIs I've used, I've never seen a GET request that required a body. – Augusto Aug 16 '15 at 14:27
  • Yep. No examples at all of GET with body content. Although it's ok as the link in the previous post mention, I will use POST for my needs. Thanks. – Johnny Aug 16 '15 at 15:30