【问题标题】:Hamcrest matcher for a String, where the String contains some random values字符串的 Hamcrest 匹配器,其中字符串包含一些随机值
【发布时间】:2011-12-21 10:17:10
【问题描述】:

有没有办法将以下字符串与任何 hamcrest 匹配器匹配。

"{\"messageType\":\"identify\",\"_id\":\"7de9a446-2ced-4bda-af35-81e95ad2dc32\",\"address\":\"192.168.0.0\",\"port\":7070}"

这个字符串被传递给一个方法。我使用 JMock 期望来匹配它。

问题:“72e3a446-2fed-4bda-ac35-34e95ab3dc32”部分是随机生成的UUID,在测试方法内部生成。是否有一个 Hamcrest 字符串匹配器可以匹配类似的东西

new StringCompositeMatcher("{\"messageType\":\"identify\",\"_id\":\"", with(any(String.class)), "\"address\":\"192.168.0.0\",\"port\":7070}" )

必须匹配预期的字符串以"{\"messageType\":\"identify\",\"_id\":\"开头,后面有任何字符串,以",\"address\":\"192.168.0.0\",\"port\":7070}"结尾

编辑:解决方案

with(allOf(new StringStartsWith("{\"messageType\":\"identify\",\"_id\":\""), new StringEndsWith("\",\"address\":\"192.168.0.0\",\"port\":7070}")))

【问题讨论】:

  • 这样写会更好allOf(startsWith("..."), endsWith("..."))

标签: java jmock matcher hamcrest


【解决方案1】:

也许最优雅的方法是使用正则表达式,尽管它没有内置的匹配器。但是,you can easily write your own

或者,您可以将startsWith()endsWith()allOf() 结合使用。

【讨论】:

    【解决方案2】:

    它看起来像 JSON。为什么不使用 JSON 解析器?

    【讨论】:

      【解决方案3】:

      对于像我这样偶然发现这篇文章的人:hamcrest 2.0 引入了一个新的匹配器:matchesPattern 来匹配正则表达式模式。以下代码应该可以工作:

      依赖:

      testCompile "org.hamcrest:hamcrest:2.0"
      

      ...

      import static org.hamcrest.Matchers.matchesPattern;
      import static org.hamcrest.MatcherAssert.assertThat;
      

      ...

      assertThat(
              "{\"messageType\":\"identify\",\"_id\":\"7de9a446-2ced-4bda-af35-81e95ad2dc32\",\"address\":\"192.168.0.0\",\"port\":7070}",
              matchesPattern("\\{\"messageType\":\"identify\",\"_id\":\"[0-9a-z-]+\",\"address\":\"192.168.0.0\",\"port\":7070\\}")
      );
      

      注意:{} 在 java 中是正则表达式字符,因此必须在匹配器字符串中进行转义。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-24
        • 1970-01-01
        • 2012-03-24
        • 1970-01-01
        • 1970-01-01
        • 2017-03-19
        相关资源
        最近更新 更多