我必须为我的其他服务实现一些JUnit测试。 例如,这是我的休息服务之一:
@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;
}
这是我对这项服务的测试:
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());
}
测试失败,出现以下错误:
com.sun.jersey.api.client.UniformInterfaceException:POST http://localhost:8080/dni-fe/home的回复状态为415 不支持的媒体类型 com.sun.jersey.api.client.WebResource.handle(WebResource.java:686)
答案 0 :(得分:1)
我很确定你必须使用.type(MediaType.APPLICATION_JSON)
,而不是.accept(
答案 1 :(得分:0)
您可以使用org.json.JSONObject中的简单JSONObject,并将数据作为toString传递给它。示例代码是
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()