我正在使用JerseyTest v2.5和Grizzly容器編寫測試。我的資源取決於在我的web.xml中定義的過濾器,所以測試失敗。JerseyTest 2.x中的過濾器
有沒有辦法在使用JerseyTest時配置servlet過濾器?
更好的是,有沒有辦法使用我的web.xml來配置servlet容器?
我正在使用JerseyTest v2.5和Grizzly容器編寫測試。我的資源取決於在我的web.xml中定義的過濾器,所以測試失敗。JerseyTest 2.x中的過濾器
有沒有辦法在使用JerseyTest時配置servlet過濾器?
更好的是,有沒有辦法使用我的web.xml來配置servlet容器?
有有關的問題已經打開,你可能已經看到:https://java.net/jira/browse/JERSEY-2259
最終,好像
您目前無法註冊的servlet和過濾器類 同時進行球衣測試框架(設置一個會擦除另一個)。
此報價取自this reply by Pavel Bucek。
我不知道你是否看到過,他似乎找到了解決方法,但我不確定這是否適用於你。
你可以做的是部署嵌入式(例如) GlassFish應用和使用用於外部 容器支持反對它運行測試。命令執行的測試將是這樣的:
球衣版本1.2+:
MVN測試
Djersey.test.containerFactory = com.sun.jersey.test.framework.spi.container。 external.ExternalTestContainerFactory
Djersey.test.port = XXX -Djersey.test.host = XXX
球衣版本1.1.5.1-:
MVN測試
Djersey.test.containerFactory = com.sun.jersey.test.framework.spi.container.external.ExternalTestContainerFactory
DJERSEY_HTTP_PORT = XXX -DJERSEY_HOST_NAME = XXX
我沒有測試它,但也許這幫助你。
具有過濾
public class MyFilter implements ContainerRequestFilter {
@Context
HttpServletRequest webRequest;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
final HttpSession session = webRequest.getSession();
......
}
}
你可以定義你的資源配置類,然後註冊您的過濾器
import org.glassfish.jersey.server.ResourceConfig;
import javax.ws.rs.ApplicationPath;
@ApplicationPath("/rest")
public class MyResourceConfig extends ResourceConfig {
// Initializes all resources from your REST package.
public MyResourceConfig() {
// add your package name to enable package scanning for resources.
packages("com.myapp.rest");
// or you can register your resource class directly
register(YourResource.class);
register(MyFilter.class);
}
}
然後,在你的球衣Test類
@Override
protected Application configure() {
return new MyResourceConfig();
}
或在更簡單的方法
@Override
protected Application configure() {
return new ResourceConfig(YourResource.class).register(MyFilter.class);
}
如果您需要設置一個屬性,以你的過濾器,你可以做
@Override
protected Application configure() {
return new MyResourceConfig().property("property", "value");
}
或
@Override
protected Application configure() {
return new ResourceConfig(YourResource.class).register(MyFilter.class).property("property", "value");
}
進一步研究此之後,它似乎是不可能的Servlet過濾器與JerseyTest結合 - 無論應該如何應用,都必須以Jersey/JAX-RS濾波器的形式實現。
要結合使用servlet過濾器進行測試,WAR必須部署在servlet容器(嵌入式或其他)中。
你使用什麼類型的過濾器?你能否請你發佈你的資源代碼和web.xml? – vzamanillo