One of the calls I have to make in my application to another system returns JSON but with the content type as:
Content-Type: text/plain;charset=UTF-8
I have managed to get my serivce to handle this by setting the ContentType of my restClient instance
def retrieveFromRESTClientJSON(String url) throws MalformedURLException, URISyntaxException {
def uri = validateUrl(url)
def restClient = new RESTClient()
log.info("REQUEST: GET request to " + uri)
restClient.setContentType("application/json")
def restClientResponse = restClient.get(uri: uri)
def restClientResponseData = restClientResponse.getData()
log.info("RESPONSE: " + restClientResponseData)
return restClientResponseData
}
I don't know how to write a unit test for this to ensure that the methods is doing as expected and returning a json object despite the Content-Type being "text/plain"
How is it I would test this?
This is currently what I have:
void "JSON in retrieveFromRESTClientJSON's response (Content-Type text/plain) can be accessed"() {
given: "A mocked response containing JSON as plain text"
def JSONasText = '{"info":{"id":"1234567","version":{"foo":"stable","number": "1.2"},"device": {"location": "GB","info": "Cats are not happy on Mondays"}}}'
def baseResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"))
RESTClient.metaClass.get { Map<String, ?> args ->
def responseDecorator = new HttpResponseDecorator(baseResponse, JSONasText)
responseDecorator.addHeader("Content-Type", "text/plain")
responseDecorator.setHeader("Content-Type", "text/plain")
return responseDecorator
}
when: "We call our service"
def responseData = service.retrieveFromRESTClientJSON("http://ift.tt/1fEzkBa")
then: "We can access all values and attributes in the returned parsed JSON"
assert responseData.info.id == "1234567"
assert responseData.info.version.foo == "stable"
assert responseData.info.version.number == "1.2"
assert responseData.info.device.location == "GB"
assert responseData.info.device.info == "Cats are not happy on Mondays"
GroovySystem.metaClassRegistry.removeMetaClass(RESTClient.class)
}
The reponse I get when I run this test is:
Failure: |
JSON in retrieveFromRESTClientJSON's response (Content-Type text/plain) can be accessed(uui.RestServiceSpec)
|
groovy.lang.MissingPropertyException: No such property: info for class: java.lang.String
at uui.RestServiceSpec.JSON in retrieveFromRESTClientJSON's response (Content-Type text/plain) can be accessed(RestServiceSpec.groovy:189)
so it looks like the restClient.setContentType("application/json")
is not working as expected and the response is being formatted as a String.
Aucun commentaire:
Enregistrer un commentaire