使用Netty在Resteasy测试中注入上下文数据

时间:2013-10-15 09:50:00

标签: java integration-testing netty resteasy

我正在使用Resteasy Docs中所述的嵌入式Netty实例尝试使用Resteasy测试资源。

注入路径参数和查询参数就像魅力一样,但后来我尝试测试从上下文中注入HttpServletRequestHttpServletResponse的资源,如下所示:

@GET
@Path("/")
public void example(@Context HttpServletResponse response, 
                    @Context HttpServletRequest request) { ... }

Resteasy在上下文中找不到HttpServletRequest并抛出以下异常:

5105 [r #1] DEB o.j.resteasy.core.SynchronousDispatcher  - PathInfo: /auth
5201 [r #1] ERR c.s.f.v.s.r.e.ApplicationExceptionMapper - Unhandled application exception: Unable to find contextual data of type: javax.servlet.http.HttpServletRequest
org.jboss.resteasy.spi.LoggableFailure: Unable to find contextual data of type: javax.servlet.http.HttpServletRequest

我尝试按照RESTEasy Mock vs. Exception Mapper vs. Context中的建议在上下文中放置模拟版本的请求和响应,但它不起作用,因为上下文数据是ThreadLocal,Netty为每个请求生成一个新线程。

关于如何解决这个问题的任何想法?

2 个答案:

答案 0 :(得分:0)

在我的案例中有效的是注入了一个org.jboss.seam.mock.HttpServletRequest,因为我在我的应用程序中使用了seam。你应该尝试一些像spring.test或mockito这样的模拟框架。

以下是我的代码的样子:

import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.mock.MockDispatcherFactory;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.jboss.resteasy.plugins.server.resourcefactory.POJOResourceFactory;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.seam.mock.MockHttpServletRequest;
import org.jboss.seam.mock.DBUnitSeamTest;

public class Test extends DBUnitSeamTest{   

    @Test
    public void test() throws Exception {

        Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();

        POJOResourceFactory noDefaults = new POJOResourceFactory(ClasstoBeTested.class);        dispatcher.getRegistry().addResourceFactory(noDefaults);
        MockHttpRequest request = MockHttpRequest.get("/serviceToBeTested/1961");
        MockHttpResponse response = new MockHttpResponse();

        HttpServletRequest servletRequest = new MockHttpServletRequest(getSession());
        ResteasyProviderFactory.getContextDataMap().put(HttpServletRequest.class, servletRequest);

        dispatcher.invoke(request, response);

        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
        Assert.assertTrue(response.getContentAsString().contains("1961")); 

    }
}

答案 1 :(得分:0)

我刚刚在另一个项目上再次受到攻击,并决定再次进行调查。

问题是在使用Netty的模拟请求中,没有a = np.asarray(arr) m,n = a.shape out = a[0] for i in range(1,m): out = out[...,None] + a[i] out.shape = out.size # Flatten 可用。如果您查看HttpServletRequest及相关类的来源,Reasteasy会对未实现NettyJaxrsServer的http请求使用自己的抽象。

如果我改变我的实现以使用这些抽象,我可以在我的资源中访问请求和响应。

HttpServletRequest

这并不完美,因为它使我的资源依赖于Resteasy接口,但我现在决定使用它来支持多部分数据的模拟测试。

相关问题