用于String的Hamcrest匹配器,其中String包含一些随机值

问题描述 投票:3回答:3

有没有办法将以下字符串与任何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}")))
java jmock matcher hamcrest
3个回答
3
投票

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

或者,你可以将startsWith()endsWith()allOf()结合起来。


3
投票

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


1
投票

对于像我这样绊倒在这个帖子上的人: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中的正则表达式字符,因此必须在匹配器字符串中进行转义。

© www.soinside.com 2019 - 2024. All rights reserved.