【问题标题】:jersey - test rest endpoint service with ejb injectionjersey - 使用 ejb 注入测试 rest 端点服务
【发布时间】:2015-09-15 08:22:00
【问题描述】:

我有一个 jax-rs 资源

@Path("rest/v1/serviceemail")
public class PreviewResource implements Preview
{  
  @EJB
  private Mapper mapper;

我正在使用 jersey-test-framework-core 和 jersey-test-framework-grizzly2 创建一个 IT 测试。

当我启动测试时,ejb 没有注入到服务中,所以我收到了 NPE。

【问题讨论】:

  • 模拟Mapper。除非您需要完整的集成测试,否则您需要可以加载完整的 EE 环境的东西。也许像 arquillian。
  • 您可以看到 here 使用 Mockito 模拟 Mapper 的一种方式
  • 我在考虑集成测试,因为单元测试已经完成;所以我想使用一个轻量级的 EE 嵌入式容器。
  • 我会去看看 arquillian。这实际上是我知道的唯一一个,所以我真的不能推荐任何其他人。

标签: jersey grizzly


【解决方案1】:

我通过实现自定义 InjectableProvider 找到了解决方案。以下代码取自Oracle article

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.ws.rs.ext.Provider;

import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.core.spi.component.ComponentScope;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.InjectableProvider;

@Provider
public class EJBProvider implements InjectableProvider<EJB, Type> {

    public Scope getScope() {
        return Scope.Singleton;
    }

    public Injectable getInjectable(ComponentContext cc, EJB ejb, Type t) {
        if (!(t instanceof Class)) return null;

        try {
            Class c = (Class)t;        
            Context ic = new InitialContext();

            final Object o = ic.lookup(c.getName());

            return new Injectable<Object>() {
                public Object getValue(HttpContext c) {
                    return o;
                }                    
            };            
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

我不得不稍微调整一下以适应我的环境。另请注意,提供者必须与您的服务类在同一个包中,否则将不会被拾取(文章中没有说)。

【讨论】:

  • 您能否提供更多详细信息或添加一个集成测试作为示例?
猜你喜欢
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多