XML/XPath Matchers for Hamcrest

The following text is a partial translation of the original English article, performed by ChatGPT (gpt-3.5-turbo) and this Jekyll plugin:

Hamcrest 是我在单元测试中最喜欢使用的工具。它用面向对象的机制取代了 org.junit.Assert 的 JUnit 过程性断言。然而,我稍后会更详细地讨论这个主题。

现在,我想展示今天在GitHub和Maven Central上发布的一个新库:jcabi-matchers。jcabi-matchers是一个集合了Hamcrest匹配器的库,用于在XML和XHTML文档中进行XPath断言。

假设,例如,正在进行测试的类生成一个需要包含一个内容为”hello, world!”的单个元素的XML。

以下是该代码在单元测试中的样子:

import com.jcabi.matchers.XhtmlMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
public class FooTest {
  @Test
  public void hasWelcomeMessage() {
    MatcherAssert.assertThat(
      new Foo().createXml(),
      XhtmlMatchers.hasXPaths(
        "/document[count(message)=1]",
        "/document/message[.='hello, world!']"
      )
    );
  }
}

我知道有两种替代方法,几乎能够完成相同的任务:David Ehringer的xml-matchers和Hamcrest本身的hasXPath()方法。

我都试过,但遇到了很多问题。

首先,Hamcrest的hasXPath()只适用于Node的实例。使用这个方法,将一个String转换为Node在每个单元测试中都成了一个重复而例行的任务。

上面的限制相比之下,Hamcrest是非常奇怪的,而jcabi-matchers可以与几乎任何东西一起使用,从StringReader,甚至是InputStream

第二,来自xml-matchersXmlMatchers提供了一种非常不方便的方式来处理命名空间。在您可以使用非默认命名空间的XPath查询之前,您应该创建一个NamespaceContext的实例。

这个库提供了这个接口的一个简单实现,但是在每个单元测试中仍然需要额外的代码。

jcabi-matchers 进一步简化了命名空间处理问题,因为它预定义了大多数常用的命名空间,包括 xhtmlxsxsl,等等。

以下示例可以直接使用,无需任何额外配置:

MatcherAssert.assertThat(
  new URL("http://www.google.com").getContent(),
  XhtmlMatchers.hasXPath("//xhtml:body")
);

总结一下,我对这个库的主要目标是使其使用简便。

Translated by ChatGPT gpt-3.5-turbo/31 on 2023-08-29 at 15:59

sixnines availability badge   GitHub stars