如何在 Jersey 单元测试框架 2.5 中设置 Servlet 上下文

dar*_*eck 5 unit-testing servlets jersey maven jersey-2.0

我有两个问题:

1)如何为扩展 JerseyTest. 从我所做的研究来看,似乎我必须创建一个TestContainerfor aTestFactory并传入 an AppDescriptor,但这似乎比应该的更复杂。还有其他建议吗?

通常,在我的 Jersey 资源类的单元测试中寻找一种设置 Servlet 上下文的方法,这通常由 web.xml 完成。

例子:

@Path(value = "/service")
public class Foo{

@Context ServletContext ctx;

@GET
@Path(value="/list")
public String list() {
    Controller ctrl = new Controller();
    ctx.setAttribute("controller", ctrl);
    return ctrl.getList();
}

}

public class FooUnitTest extends JerseyTest
{
    @Test
    public void testService()
    {

         //set/how to configure the context?
    }
}
Run Code Online (Sandbox Code Playgroud)

目标是模拟控制器,以便我可以将其传递到上下文中。

2)使用球衣测试与

<dependency>
    <groupId>com.sun.jersey.jersey-test-framework</groupId>
    <artifactId>jersey-test-framework-grizzly</artifactId>
    <version>1.5-SNAPSHOT</version>
    <scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

对比

<dependency>
    <groupId>org.glassfish.jersey.test-framework.providers</groupId>
    <artifactId>jersey-test-framework-provider-bundle</artifactId>
    <version>2.4.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

这是 Jersey 框架 2.5

小智 -2

您可以使用org.springframework.mock.web.MockServletContext类来模拟 servlet 上下文。它是Spring框架的一部分。

模拟ServletContext