我可能完全错过了一些东西,但我无法按照我想要的方式测试我的路线。
我有以下 bean:
@Component("fileProcessor")
public class FileProcessor {
public boolean valid(@Header("customObject) CustomObject customObject,Exchange exchange) throws IOException{
return false;
}
我有一个像这样调用我的 bean 的路由:
from("direct:validationFile").routeId("validationFile").validate().method("fileProcessor","valid")
// Other stuff
.end();
这是我的单元测试,基于我发现的示例:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class})
@ContextConfiguration(locations = { "classpath:/tu-dao-beans.xml" })
public class FileProcessorTest extends CamelTestSupport {
@EndpointInject(uri = "mock:result")
protected MockEndpoint resultEndpoint;
@Produce(uri = "direct:start")
protected ProducerTemplate template;
@Override
public boolean isDumpRouteCoverage() {
return true;
}
@Test
public void testSendMatchingMessage() throws Exception {
String expectedBody = "<matched/>";
resultEndpoint.expectedBodiesReceived(expectedBody);
template.sendBodyAndHeader(expectedBody, "foo", "bar");
resultEndpoint.assertIsSatisfied();
}
@Test
public void testSendNotMatchingMessage() throws Exception {
resultEndpoint.expectedMessageCount(0);
template.sendBodyAndHeader("<notMatched/>", "foo", "notMatchedHeaderValue");
resultEndpoint.assertIsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
// from("direct:start").filter(header("foo").isEqualTo("bar")).to("mock:result");
from("direct:start").routeId("validationFile").validate().method("fileProcessor","valid").to("mock:result");
}
};
}
}
测试失败,因为找不到 fileProcessor
,但我很确定我的 spring 上下文
已正确加载,我正在使用相同的 bean。我的
文件和我的 DAO 组件都很好......我缺少什么?dbunit
测试的 xml
编辑: 感谢 Jérémis B 的回答,我轻松解决了我的问题。万一有人像我一样绊倒,这里是我添加的代码:
@Autowired
private FileProcessor fileProcessor;
@Override
protected JndiRegistry createRegistry() throws Exception {
JndiRegistry registry = super.createRegistry();
registry.bind("fileProcessor", fileProcessor);
return registry;
}
最佳答案
您可以看到official documentation使用 Spring 进行“如何”测试。
在您的示例中,您创建了一个 Spring Context,但使用了 CamelTestSupport
:此类创建了一个不知道 Spring Context 的 CamelContext。此上下文看不到 bean“fileProcessor”。
有很多方法可以进行此类测试。使用您已有的代码,最简单的方法可能是:
- 使用 @Autowire 在您的测试类中注入(inject) fileProcessor
- 重写
createRegistry
并将fileProcessor添加到注册表
您也可以重写CamelSpringTestSupport
并实现createApplicationContext
。另一种方法是将路由定义保存在 Spring Bean 中(通过 xml 或 RouteBuilder),然后注入(inject)测试 MockEndpoint
或 ProducerTemplate
。
关于java - Camel处理器单元/集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36091618/