Jane Nicholson
Jane Nicholson

Reputation: 385

Test putting badly formed json using JerseyInvocation builder

I'm trying to write an integration test to ensure that my dropwizard application is returning appropriate error codes. One of the scenarios includes ensuring that if the object being PUT is not deserialisable, I get a reasonable error response.

I can't find a way using JerseyInvocation.Builder to PUT a badly-formed JSON entity. The only way to create an Entity appears to be by having an object of the correct type, which obviously will deserialise. I want to be able to create an entity whose serialised value is an arbitrary string that I provide.

I've tried putting objects of the wrong type, but that doesn't test all of the edge cases I want to test. I also want to avoid creating a lot of types that are subtly different from the object the API is expecting.

Can anyone suggest a way of achieving what I want?

Update: this is the code I'm using at the moment:

JerseyInvocation.Builder request; // initialised elsewhere and not interesting

is = new ClassPathResource(nameOfFileContainingWellFormedJson, MyEntityClsss.class).getInputStream(); entity = Entity.entity(is, MediaType.APPLICATION_JSON); request.put(entity); This response should be returning 200 and is returning 400.

is = new ClassPathResource(nameOfFileContainingBadlyFormedJson, MyEntityClsss.class).getInputStream(); entity = Entity.entity(is, MediaType.APPLICATION_JSON); request.put(entity); This response is returning 400, but until the above is returning 200 it's not doing so for the right reasons.

Upvotes: 0

Views: 120

Answers (1)

Frederik Heremans
Frederik Heremans

Reputation: 658

You can use the Jersey Entity class, used for raw streams of any mime-type. Something like:

ByteArrayInputStream bais = new ByteArrayInputStream("{\"malformattedJson".getBytes());
builder.post(Entity.entity(bais, "application/json"));

Or load the malformed JSON from a file/classpath resource in your tests to ditch the double quote escaping 😉

Upvotes: 2

Related Questions