【问题标题】:How to send/accept JSON using JerseyTest Framework如何使用 JerseyTest 框架发送/接受 JSON
【发布时间】:2015-10-18 18:49:33
【问题描述】:

我正在尝试编写一个简单的测试类来模拟 RESTful Web 服务,通过 POST 方法创建客户。以下在assertEquals 失败,我收到400 Bad Request 响应。我不能使用调试器来观察堆栈跟踪。但是控制台告诉我以下...

信息:已启动监听器绑定到 [localhost:9998]
信息:[HttpServer] 已启动。

public class SimpleTest extends JerseyTestNg.ContainerPerMethodTest {

    public class Customer {
        public Customer() {}

        public Customer(String name, int id) {
            this.name = name;
            this.id = id;
        }

        @JsonProperty("name")
        private String name;

        @JsonProperty("id")
        private int id;
    }

    @Override
    protected Application configure() {
        return new ResourceConfig(MyService.class);
    }

    @Path("hello")
    public static class MyService {
        @POST
        @Consumes(MediaType.APPLICATION_JSON)
        public final Response createCustomer(Customer customer) {
            System.out.println("Customer data: " + customer.toString());
            return Response.ok("customer created").build();
        }
    }

    @Test
    private void test() {
        String json =   "{" +
                "\"name\": \"bill\", " +
                "\"id\": 4" +
                "}";
        final Response response = target("hello").request(MediaType.APPLICATION_JSON_TYPE).post(Entity.json(json));
        System.out.println(response.toString());
        assertEquals(response.getStatus(), 200);
    }
}

【问题讨论】:

    标签: json jersey testng jersey-client jersey-test-framework


    【解决方案1】:

    您可以使用response.readEntity(String.class) 读取实际正文,而不是打印response.toString()。您会在正文中找到来自 Jackson 的错误消息

    没有找到适合类型 [simple type, class simple.SimpleTest$Customer] 的构造函数:无法从 JSON 对象实例化(需要添加/启用类型信息?)

    乍一看你的Customer 类看起来不错;它有一个默认构造函数。但真正的问题是杰克逊无法实例化它,因为它是一个非静态内部类。所以要修复它,只需将Customer 类设为static

    public static class Customer {}
    

    作为一般规则,在使用 JSON 和 Jackson 和 Jersey 工作时,通常当你得到 400 时,这对 Jackson 来说是个问题,而 Jackson 非常擅长吐出有助于我们调试的有意义的消息。

    【讨论】:

    • 你是个了不起的人。你刚刚解决了一个困扰我超过 6 个小时的问题。谢谢你
    • @JasonJavier 谢谢MCVE。这就是我试图鼓励提出与泽西岛相关的问题的方式。我们可以复制并粘贴到单个类中进行测试。即使问题与测试框架无关,将所有功能放入一个可运行的测试中也有助于更快地找出问题。它还有助于 OP 缩小问题范围,从而使调试更加集中。
    猜你喜欢
    • 2016-05-28
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 2017-11-28
    • 2012-05-02
    • 2011-05-18
    • 2014-12-18
    • 2016-12-20
    相关资源
    最近更新 更多