使用spring配置的camelContext模拟Camel端点

时间:2012-02-28 15:04:07

标签: java spring junit integration-testing apache-camel

我正试图找出在使用弹簧测试支持的集成测试中模拟端点的“正确”方法。

代码正在运行,但我想知道这是否是正确的方法。我看过驼峰测试测试工具包,它是adviceWith,但是当spring负责在测试中加载camelContex时,这没用,对吗?

这就是我所拥有的:

服务:

@Service
public class FtpOutboundFileStrategy implements OutboundFileExportStrategy {
    private final String FTP_PATTERN= "{0}://{1}@{2}";
    private final ProducerTemplate producerTemplate;

    @Autowired
    public FtpOutboundPriceFileStrategy(ProducerTemplate producerTemplate) {
        this.producerTemplate = producerTemplate;
    }

    @Override
    public void doExport(OutboundFile file, ExportProperties exportProperties) {
        this.producerTemplate.sendBodyAndHeader(createFtpUri(exportProperties),
                file.getFileContent(), Exchange.FILE_NAME, file.getFileName());
    }
}

集成测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:testDB.xml", "classpath:applicationContext.xml"})
public class FtpOutboundFileStrategyIT {

    @EndpointInject(uri = "mock:ftp")
    protected MockEndpoint fakeEndpoint;

    @Autowired
    FtpOutboundFileStrategy ftpOutboundPriceFileStrategy;

    @Autowired
    protected CamelContext camelContext;

    @DirtiesContext
    @Test
    public void directsToFtpEndpoint() throws Exception {
        camelContext.addEndpoint("ftp://foo@localhost", fakeEndpoint);

        fakeEndpoint.expectedBodyReceived().equals("This is the file");
        ftpOutboundPriceFileStrategy.doExport(new OutboundFile("This is the file"),
                new ExportProperties("foo", "localhost"));
        fakeEndpoint.assertIsSatisfied();
    }
}

现在,这有效,但我想知道这是否是一种黑客攻击:

camelContext.addEndpoint("ftp://foo@localhost", fakeEndpoint);

我在某处读到使用@EndpointInject(uri = "mock:ftp")会创建一个模拟端点,其中存在更高的默认FtpEndpoint,但如果我将其删除,则测试失败,因为它使用默认值。

另一个奇怪的事情是,如果我在模拟uri中使用“ftp *”而不是“ftp:// foo @ localhost”,测试也会失败,这让我相信这不是正确的做法。

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:3)

我认为David Valeri正在努力改进驼峰测试弹簧,以便能够使用纯弹簧测试套件做更多的Camel。有一张JIRA票,所以请留意未来的改进。

首先虽然你可以使用Spring属性占位符来替换端点uris,所以在运行测试时,你可以用实际的ftp端点替换模拟端点等。

请参阅此常见问题解答,了解Spring XML限制 http://camel.apache.org/how-do-i-use-spring-property-placeholder-with-camel-xml.html

Camel in Action一书中的第6章,还介绍了如何使用Spring属性占位符进行测试,以及包含实际端点uris的test.properties和production.properties文件。

替代您的测试方法,您可以使用Camel advice-with API在运行测试之前更改路由和诸如此类的东西。详情请见http://camel.apache.org/advicewith.html

答案 1 :(得分:0)

我使用Camel(> 2.7)的 mockAllEndpoints 新功能编写了a small article。 您还可以找到官方文档here

答案 2 :(得分:0)

尝试使用

扩展测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyConfigurationClass.class)
//this could be an xml file as well with locations attribute
public class CamelRoutesTest extends AbstractJUnit4SpringContextTests{

我有类似的问题。这修复了camelContext和applicationContext相关的问题