我可能完全错过了一些东西,但我无法按照自己的意愿测试我的路线。
我有以下bean:
@Component("fileProcessor")
public class FileProcessor {
public boolean valid(@Header("customObject) CustomObject customObject,Exchange exchange) throws IOException{
return false;
}
我有一条叫我豆子的路线:
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 context
已正确加载,我正在为beans.xml
使用相同的dbunit
文件测试和我的DAO组件都很好......我缺少什么?
编辑: 感谢JérémisB的回答,我很容易解决问题。如果我在这里遇到绊倒的是我添加的代码:
@Autowired
private FileProcessor fileProcessor;
@Override
protected JndiRegistry createRegistry() throws Exception {
JndiRegistry registry = super.createRegistry();
registry.bind("fileProcessor", fileProcessor);
return registry;
}
答案 0 :(得分:5)
您可以看到official documentation的“如何”测试Spring。
在您的示例中,您创建了一个Spring Context,但使用CamelTestSupport
:此类创建一个不知道Spring Context的CamelContext。此上下文不会看到bean“fileProcessor”。
有很多方法可以进行这种测试。使用您已有的代码,最简单的可能是:
createRegistry
并将fileProcessor添加到注册表您也可以覆盖CamelSpringTestSupport
并实施createApplicationContext
。另一种方法是将路由定义保存在Spring Bean中(通过xml或RouteBuilder),并注入测试MockEndpoint
或ProducerTemplate
。