1

有没有办法在 Camel Junit 中比较 XML 消息?

我正在使用以下代码:

@RunWith(CamelSpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:camel-context-test.xml" })
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@MockEndpoints("*")
public class CamelRoutesTest/* extends XMLTestCase */{
    private static final Log LOG = LogFactory.getLog(CamelRoutesTest.class);
    @Autowired
    protected CamelContext camelContext;

    @EndpointInject(uri = "mock:d2")
    protected MockEndpoint direct1;

    @Produce(uri = "direct:d1")
    protected ProducerTemplate d1;

    @Test
    public void test1() throws Exception {
        LOG.info("Starting testTradeSaveToPL test");

            //node1 comes BEFORE node2
    String sendMsg = "<test><node1>1</node1><node2>2</node2></test>"; 

            //node1 comes AFTER node2
    String valMsg1 = "<test><node2>2</node2><node1>1</node1></test>";


        direct1.expectedBodiesReceivedInAnyOrder(valMsg1);

        d1.sendBody(sendMsg);
        direct1.assertIsSatisfied(camelContext);
    }
}

我的问题是,在我发送到路由的 XML 消息中,node1 在 node2 之前,而在回复中 node2 在 node1 之前。

通过查看,我知道两个 XML 都是相等的,但是由于代码进行了字符串比较,所以它失败了。

我知道 XMLJUnit 比较工具,但是如何将它集成到给定的测试用例中?

4

1 回答 1

3

我在我的 Camel 单元测试中集成了 XMLUnit 来比较 XML 消息。

在您的构造函数中,设置 XMLUnit:

@Override
public void setUp() throws Exception {
    super.setUp();

    //Tell XML Unit to ignore whitespace between elements and within elements
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setNormalizeWhitespace(true);
}

然后稍后您可以运行断言:

    Diff myDiff = new Diff(actualResponse, expectedResponseAsString);
    assertTrue("XML identical " + myDiff.toString(),
                   myDiff.identical());

您可以使用此依赖项:

    <dependency>
        <groupId>xmlunit</groupId>
        <artifactId>xmlunit</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>   

这是用户指南的链接:

http://xmlunit.sourceforge.net/userguide/html/index.html

由于元素的顺序实际上是不同的,这个测试框架可能对你没有帮助。但是,您也可以只使用 Java 或 JDOM 中的 XPath API 来运行您的断言。

谢谢,约格什

于 2012-12-07T18:32:22.433 回答