简体   繁体   English

测试异步JAX-RS方法

[英]Test asynchronous JAX-RS method

Consider an asynchronous JAX-RS method, part of an OkResource : 考虑异步的JAX-RS方法,它是OkResource一部分:

@GET
@Path("/ok")
@ManagedAsync
public void getOk(@Suspended final AsyncResponse asyncResponse) {
    asyncResponse.resume("OK");
}

Dropwizard, based on Jersey, provides the useful ResourceTestRule . 基于Jersey的Dropwizard提供了有用的ResourceTestRule A test class for the above method would contain an instance of this rule. 上述方法的测试类将包含此规则的一个实例。

@ClassRule
public static ResourceTestRule RULE = ResourceTestRule.builder()
  .addResource(new OkResource())
  .build();

A test method for the JAX-Rs method would look like JAX-Rs方法的测试方法如下所示

@Test
public void testGetOk()  {
    Response response = RULE.target("/ok).request().get();
    // assert ...
}

For synchronous JAX-RS methods this works fine. 对于同步 JAX-RS方法,这可以正常工作。 But for asynchronous JAX-RS like above this approach does not work: 但是对于像上面这样的异步 JAX-RS,此方法不起作用:

WARN [2019-06-26 09:15:15,811] org.glassfish.jersey.test.inmemory.InMemoryConnector: Asynchronous server side invocations are not supported by InMemoryContainer. WARN [2019-06-26 09:15:15,811] org.glassfish.jersey.test.inmemory.InMemoryConnector:InMemoryContainer不支持异步服务器端调用。

Is there a different way to test asynchronous JAX-RS methods without having to directly call the method ( getOk in this case) with a mocked AsyncResponse ? 是否有另一种方法来测试异步JAX-RS方法,而不必使用getOk AsyncResponse直接调用该方法(在本例中为getOk )?

The Dropwizard documentation tells us what to do: Dropwizard文档告诉我们该怎么做:

  • add a Maven dependency for a TestContainerFactory TestContainerFactory添加Maven依赖项
  • set it while building the ResourceTestRule : 在构建ResourceTestRule
@ClassRule
public static ResourceTestRule RULE = ResourceTestRule.builder()
  .setTestContainerFactory(new GrizzlyWebTestContainerFactory())
  .addResource(new OkResource()).build();

The Jersey documentation describes more SPIs . Jersey文档描述了更多SPI

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM