当用于在单元测试中的新JndiContext中构造bean时,ProducerTemplate为null

时间:2014-09-15 15:00:05

标签: java unit-testing apache-camel

当用于在单元测试中的新JndiContext中构造bean时,ProducerTemplate为null

我正在尝试对使用bean动态构建sftp端点的路由进行单元测试。这在我在正常上下文中运行路由时起作用,因为看起来模板已经在注册表中并且可以正确注入。

我的问题是,在尝试构建单元测试时,我似乎遇到了一个条件,当调用createJndiContext时,ProducerTemplate仍为null,并导致我的bean中需要调用方法的NPE在模板上。

非常感谢任何帮助。

这是一个简化的单元测试,用于说明这一点:

public class BeanWithProdTemplateDependencyTest
  extends CamelTestSupport
{

  private static final Logger log = LoggerFactory.getLogger(BeanWithProdTemplateDependencyTest.class);
  private static final String FROM = "direct:start";

  @EndpointInject(uri = "mock:result")
  protected MockEndpoint resultEndpoint;

  @Before
  public void setUp() throws Exception {

    super.setUp();
    context.getRouteDefinition("my-cool-route").adviceWith(context, new AdviceWithRouteBuilder()
    {

      @Override
      public void configure()
        throws Exception
      {
        replaceFromWith(FROM);

      }
    });
    startCamelContext();

  }

  @Test
  public void test()
  {
    template.sendBody(FROM, "cheese");
  }

  @Override
  public boolean isUseAdviceWith()
  {
    return true;
  }

  @Override
  protected Context createJndiContext()
    throws Exception
  {
    JndiContext context = new JndiContext();
    MyBean myBean = new MyBean(template);
    context.bind("myBean", myBean);

    return context;
  }

  @Override
  protected RouteBuilder createRouteBuilder()
    throws Exception
  {
    return new RouteBuilder()
    {

      @Override
      public void configure()
        throws Exception
      {
        from("jms:queue:inbox")
        .routeId("my-cool-route")
        .beanRef("myBean", "doStuff")
        .log("Body: $body}")
        .to("mock:result");
      }
    };
  }

  public class MyBean {

    private final ProducerTemplate producerTemplate;
    public MyBean(ProducerTemplate template)
    {
      this.producerTemplate = template;
    }

    public void doStuff() throws Exception{
      // NPE here, template is null
      this.producerTemplate.sendBody("seda:foo", "beer");
    }
  }
}

1 个答案:

答案 0 :(得分:1)

我找到了一点help from here的解决方法。

我试图太快做太多。我删除了createJndiContext()的覆盖,并在测试中将这些行添加到setUp()方法中:

MyBean myBean = new MyBean(template);

JndiRegistry registry = (JndiRegistry) (
    (PropertyPlaceholderDelegateRegistry)context.getRegistry()).getRegistry();
registry.bind("myBean", myBean);

这允许我使用非null的ProducerTemplate创建我的bean并将其推送到由CamelTestSupport.setUp()

创建的注册表中