Kong / unirest-java

Unirest in Java: Simplified, lightweight HTTP client library.
http://kong.github.io/unirest-java/
MIT License
2.59k stars 593 forks source link

[UnirestMock] thenReturn(Object pojo) assumes JSON serialization #394

Closed Tazaf closed 3 years ago

Tazaf commented 3 years ago

Is your feature request related to a problem? Please describe. I'm working against a REST Api that (sadly) only returns XML formatted responses and I wanted to use UnirestMock in my tests, notably the thenReturn(Object pojo) method.

Alas, that can not work as, like the title says, the thenReturn(Object pojo) method serializes the provided Object pojo to a JSON string as the response's body: https://github.com/Kong/unirest-java/blob/685d8f843d155db3ea4dafce934f342a2b6f2c71/unirest-mocks/src/main/java/kong/unirest/Invocation.java#L75

The Unirest instance I'm mocking in my tests has been configured to use Jackson XmlMapper, thus when processing the MockRawResponse to produce an ObjectResponse:

https://github.com/Kong/unirest-java/blob/685d8f843d155db3ea4dafce934f342a2b6f2c71/unirest/src/main/java/kong/unirest/ObjectResponse.java#L41

It fails due to a parsing exception:

"com.fasterxml.jackson.core.JsonParseException: Unexpected character '{' (code 123) in prolog; expected '<' at [row,col {unknown-source}]: [1,1]"

And of course it does: my ObjectMapper expects some XML and is provided JSON instead

As a consequence, the body of the response is null and my test fails.

Describe the solution you'd like I'd like to be able to somehow provide a custom ObjectMapper to a MockClient instance, that will be used when serialiazing POJOs.

Something like (or anything else that makes more sense):

this.instanceMock = MockClient.register(this.customInstance, new CustomObjectMapper());

Describe alternatives you've considered Of course, I could simply the XML I want to see returned as a String argument to the `thenReturn(String body) but... I'd very much like not to do that 😅 (I'll do that in the meantime, though, but still)

ryber commented 3 years ago

What if it used the ObjectMapper that was configured with Unirest? No need for a different one.

Tazaf commented 3 years ago

I've got no objection with that 😃 Even easier for me.

Don't know if it could be relevant for the matter at hand, but in my app I'm managing several distinct Unirest instances with their own config (roughly one per API I'm working with) and almost never using the static one.

ryber commented 3 years ago

Complete in v3.11.10. It will try in order:

  1. The request ObjectMapper
  2. The Config ObjectMapper
  3. A JsonObjectMapper (this is probably impossible as the system will have either 1 or 2)
Tazaf commented 3 years ago

Works like a charm 💪

Many thanks!