3

I have to implement some JUnit tests for my rest services. For instance this is one of my Rest services:

@Path("/dni-fe")
public class HelloWorld
{

    @POST
    @Path("/home")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)

    public MachineResponse doMachineRegister(MachineBean machineBean)
    {
        MachineResponse response = new MachineResponse();
        String name = machineBean.getName();
        String country = machineBean.getCountry();
        String company = machineBean.getCompany();
        String model = machineBean.getModel();

    //make some stuff and some queries on db to populate the response object
    return response;
    }

And here is my test on this service:

public class MachineResponseTest {

    private static final String BASE_URI = "http://localhost:8080/dni-fe/home"

    @Test
    public void testDevice() {

        WebResource resource = Client.create().resource(BASE_URI);
        resource.accept(MediaType.APPLICATION_JSON);

        StringBuilder sb = new StringBuilder();
        sb.append("{\"name\":\"123456\",\n");
        sb.append(" \"country\":\"Spain\",\n");
        sb.append(" \"company\":\"xxx\",\n");
        sb.append(" \"model\":\"1.10.0\"\n}");      

        MachineResponse result = resource.post(MachineResponse.class,sb.toString());
    }

The test fails with the following error:

com.sun.jersey.api.client.UniformInterfaceException: POST http://localhost:8080/dni-fe/home returned a response status of 415 Unsupported Media Type at com.sun.jersey.api.client.WebResource.handle(WebResource.java:686)

harry-potter
  • 1,981
  • 5
  • 29
  • 55
  • Why are you using `MachineResponse` class in `post` method and pass string as second parameter? – Maxim Jan 04 '17 at 16:52
  • The string is the json to pass in the payload of my http request. – harry-potter Jan 04 '17 at 16:55
  • You didn't set the post's content-type. The default is not application/json, so your web service complains. Actually it's a good test... of the rest framework. – RealSkeptic Jan 04 '17 at 17:06
  • I don't understand why there is not the auto-serialization from object to JSON and viceversa. I solved my problem transforming my String in a JSON object using `org.codehaus.jettison.json.JSONObject`. Now I have to understand how to enable auto convert from object to json and viceversa. – harry-potter Jan 04 '17 at 17:34

2 Answers2

1

I am fairly sure you have to use .type(MediaType.APPLICATION_JSON), not .accept(

stelar7
  • 336
  • 1
  • 3
  • 14
0

You can use simple JSONObject from org.json.JSONObject and pass data as toString of it. Sample code is

JSONObject address = new JSONObject();
address.put("line1", address1);
address.put("line2", address2);
address.put("city", city);
address.put("state", state);
address.put("postalCode", zip);
address.put("country", "US");
address.toString()