java - 为休息服务实现 JUnit 测试

标签 java rest jersey junit4 jersey-client

我必须为我的其余服务实现一些 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 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(

关于java - 为休息服务实现 JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41469143/

相关文章:

java - 我可以将 for each 用于两个相同大小的数组吗

rest - AngularJS Controller /服务/http 通信

asp.net - 摆脱使用序列化类中的 DataContract 创建的 XML 中的 d2p1

node.js - REST HTTP 错误状态代码 Mongoose

java - 带有 Java 5 的 Jersey

java - 如何在 GlassFish 上指定过滤器映射的顺序?

java - 在我的 Java 应用程序中集成 IM/聊天功能

java - 确定字符串中的每个字符是否包含全角字符

java - StreamCorruptedException : invalid stream header:

java - 线程 "main"javax.ws.rs.NotAcceptableException : HTTP 406 Not Acceptable 中的异常