单元测试@Suspended AsyncResponse控制器

Bar*_*rry 4 java junit unit-testing jersey dropwizard

我升级到完全异步,我有一个exsiting测试,单元测试控制器与模拟依赖项并测试各种路径.我无法弄清楚如何转换此单元测试.我正在使用dropwizard/jersey,我想测试的方法现在看起来像这样

 @POST
public void getPostExample(final Map body, @Suspended final AsyncResponse
 asyncResponse){}
Run Code Online (Sandbox Code Playgroud)

旧测试使用mockito/junit并@InjectMocks用于控制器,然后调用该方法getPostExample并在响应上声明一些信息.它调用的服务是模拟的,但是当我搜索如何手动获取它以返回数据时,我找不到太多.我可以访问AsyncResponse但是在实际代码中调用带有结果的简历.我应该在测试中调用简历吗?

Pau*_*tha 7

"我应该在测试中调用简历".不.您应该做的是测试resume使用预期参数调用方法.这是测试方法行为的方法.

你可以做的是使用Mockito的ArgumentCaptor来捕获Response传递给resume方法的那个,然后对它做出断言Response.你需要嘲笑AsyncResponse这个才能工作.以下是一个例子

@RunWith(MockitoJUnitRunner.class)
public class AsyncMockTest {

    @Mock
    private AsyncResponse response;

    @Captor
    private ArgumentCaptor<Response> captor;

    @Test
    public void testAsyncResponse() {
        final TestResource resource = new TestResource();
        resource.get(this.response);

        Mockito.verify(this.response).resume(this.captor.capture());
        final Response res = this.captor.getValue();

        assertThat(res.getEntity()).isEqualTo("Testing");
        assertThat(res.getStatus()).isEqualTo(200);
    }

    @Path("test")
    public static class TestResource {
        @GET
        @ManagedAsync
        public void get(@Suspended AsyncResponse response) {
            response.resume(Response.ok("Testing").build());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)