为其余服务实现JUnit测试 [英] Implement a JUnit test for a rest service
问题描述
我必须为我的其余服务实现一些JUnit测试. 例如,这是我的Rest服务之一:
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 返回的响应状态为415 不受支持的媒体类型,位于 com.sun.jersey.api.client.WebResource.handle(WebResource.java:686)
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)
推荐答案
我非常确定您必须使用.type(MediaType.APPLICATION_JSON)
而不是.accept(
I am fairly sure you have to use .type(MediaType.APPLICATION_JSON)
, not .accept(
这篇关于为其余服务实现JUnit测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!