2011-12-21 105 views
3

有没有办法将以下字符串与任何hamcrest匹配器进行匹配。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}"))) 
+0

这将是更好的写作'allOf(startsWith( “... ”),的endsWith(“ ...”))'。 – 2011-12-24 05:13:33

回答

3

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

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

3

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

相关问题