gpt4 book ai didi

java - ProducerTemplate 在单元测试中用于在 new JndiContext 中构造 bean 时为 null

转载 作者:太空宇宙 更新时间:2023-11-04 06:32:56 24 4
gpt4 key购买 nike

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

我正在尝试对使用 bean 动态构建 sftp 端点的路由进行单元测试。当我在正常上下文中运行我的路线时,这是有效的,因为模板似乎已经在注册表中并且可以正确注入(inject)。

我的问题是,当尝试构建单元测试时,我似乎遇到了这样的情况:当调用 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");
}
}
}

最佳答案

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

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

MyBean myBean = new MyBean(template);

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

这使我能够使用非空 ProducerTemplate 创建 bean 并将其推送到由 CamelTestSupport.setUp() 创建的注册表中

关于java - ProducerTemplate 在单元测试中用于在 new JndiContext 中构造 bean 时为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25851033/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com