泽西测试与shiro

时间:2017-04-22 11:14:13

标签: java jersey-2.0 shiro jersey-test-framework

使用此类

实例化JerseyTest
public class NMAAbstractRestTest extends JerseyTest {

  @Override
  protected Application configure() {
    NMAdaptorApplication application = new NMAdaptorApplication();
    return application;
  }

}

NMAdaptorApplication构造函数。

public NMAdaptorApplication() {
    log.info("NM-Adaptor-Application is being initilized....");
    register(NMRestExceptionMapper.class);
    register(ShiroFeature.class);
    register(NMMarshallingFeature.class);
    register(new LoggingFeature(java.util.logging.Logger.getLogger("nma"), LoggingFeature.Verbosity.PAYLOAD_ANY));
    packages(true, "com.retailwave.rwos.nma.rest.resource");
    loadProperties();

}

执行以下测试方法时

@Test
public void makeOrder()
{  
   ...
   Entity entity = Entity.entity(orderContent, MediaType.APPLICATION_JSON);
   WebTarget target = target("customerorders");
   target.path("");
   target.queryParam("cmd", "create");
   target.queryParam("branchCode", "610");
   arget.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_BASIC_USERNAME, "admin");
   target.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_BASIC_PASSWORD, "admin");
   Response response = target.request().post(entity);
}

获得以下异常

  

16:34:23.893错误[grizzly-http-server-0] crrneNMRestExceptionMapper - 在Mapper捕获的异常:没有可以访问的调用代码的SecurityManager,或者绑定到org.apache.shiro.util.ThreadContext或作为vm静态单例。这是一个无效的应用程序配置。   org.apache.shiro.UnavailableSecurityManagerException:调用代码无法访问的SecurityManager,无论是绑定到org.apache.shiro.util.ThreadContext还是作为vm静态单例。这是一个无效的应用程序配置。       在org.apache.shiro.SecurityUtils.getSecurityManager(SecurityUtils.java:123)       在org.apache.shiro.subject.Subject $ Builder。(Subject.java:627)

我想这是由于我在web.xml中配置的Shiro过滤器

 <filter>
    <filter-name>ShiroFilter</filter-name>
    <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
 </filter>

<filter-mapping>
    <filter-name>ShiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
 </filter-mapping>

而JUnit测试失败了。是否有任何选项可以在JerseyTest中包含web.xml

1 个答案:

答案 0 :(得分:2)

我不知道这是否能解决问题,因为我不使用Shiro,但是如果你想配置在web.xml中配置的东西,你需要做一个更多的工作。

首先需要在servlet容器中运行测试。假设您正在使用Grizzly(注意,这不可能使用内存提供程序),您需要使用GrizzlyWebTestContainerFactory

@Override
protected TestContainerFactory getTestContainerFactory() {
    return new GrizzlyWebTestContainerFactory();
}

然后您需要配置DeploymentContext。这是您可以进行servlet容器配置的地方

@Override
protected DeploymentContext configureDeployment() {
    // just configure the ResourceConfig here instead of the `configure`.
    final ResourceConfig config = new ResourceConfig();
    return ServletDeploymentContext
            .forServlet(new ServletContainer(config))
            .addFilter(ShiroFilter.class, "ShiroFilter")
            .build();
}

另见:

相关问题