如何在 Jersey-Test 中发布 JSON 请求

Van*_*avv 6 java json jersey

我正在为我的 REST 应用程序编写单元测试,但我被卡住了。当我使用标题参数时,测试很明显。但是现在,我的请求是 JSON,我不知道如何测试它。也许有一种方法可以用泽西岛或者杰克逊来做到这一点。我从我的资源获得响应的行如下所示:

final Response response = RULE.getJerseyTest().target("/actors/1").request().post(/* json request */);
Run Code Online (Sandbox Code Playgroud)

其中 RULE 是 ResourceTestRule。

我应该怎么做才能让它发布资源?

Pau*_*tha 6

一旦你调用request()WebTargettarget("/actors/1")),你回来了Invocation.Builder,它扩展SyncInvoker。如果您查看 上的所有post()方法SyncInvoker,您会发现它们都采用Entity

  • Response post(Entity<?> entity)
  • <T> T post(Entity<?> entity, Class<T> responseType)
  • <T> T post(Entity<?> entity, GenericType<T> responseType)

如果您查看Entity该类,您只会看到一堆静态方法,例如form, html, json, xml, text。只需将您的实体 (JSON POJO) 传递给json方法即可创建一个Entityof type application/json

...request().post(Entity.json(yourPojo));
Run Code Online (Sandbox Code Playgroud)

您应该浏览我提供的所有 javadoc 链接以熟悉 API,至少这样您就知道所有这些链接的方法调用背后发生了什么。