一个字符串的Hamcrest匹配器,其中字符串包含一些随机值



是否有办法将以下字符串与任何hamcrest匹配器匹配?

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

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

问题:"72e3a446- 2feed -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}")))

也许最优雅的方法是使用regexp,尽管没有内置的匹配器。但是,您可以轻松地自己编写。

也可以将startsWith()endsWith()allOf()组合使用

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

对于像我一样偶然看到这篇文章的人:hamcrest 2.0引入了一个新的matcher: matchesPattern来匹配regex模式。下面的代码应该可以工作:

依赖性:

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中的正则表达式字符,因此必须在匹配字符串中进行转义。

最新更新