字符串的 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}")))
Is there a way to match the following string with any of the hamcrest matchers.
"{\"messageType\":\"identify\",\"_id\":\"7de9a446-2ced-4bda-af35-81e95ad2dc32\",\"address\":\"192.168.0.0\",\"port\":7070}"
This string is passed to a method. I use JMock expectations to match it.
The problem: "72e3a446-2fed-4bda-ac35-34e95ab3dc32" part is random generated UUID, which is generated inside the tested method. Is there a Hamcrest String matcher which will match something like
new StringCompositeMatcher("{\"messageType\":\"identify\",\"_id\":\"", with(any(String.class)), "\"address\":\"192.168.0.0\",\"port\":7070}" )
It must match that the expected string begins with "{\"messageType\":\"identify\",\"_id\":\"
there is any string after that, and ends with the ",\"address\":\"192.168.0.0\",\"port\":7070}"
EDIT: The solution
with(allOf(new StringStartsWith("{\"messageType\":\"identify\",\"_id\":\""), new StringEndsWith("\",\"address\":\"192.168.0.0\",\"port\":7070}")))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许最优雅的方法是使用正则表达式,尽管没有内置的匹配器。但是,您可以轻松编写自己的。
或者,您可以将
startsWith()
和endsWith()
与allOf()
结合起来。Perhaps the most elegant way to do it would be to use regexp, though there is no built-in matcher for it. However, you can easily write your own.
Alternatively, you can combine
startsWith()
andendsWith()
withallOf()
.它看起来像 JSON。为什么不使用 JSON 解析器?
It looks like JSON. Why not use a JSON parser?
对于像我一样偶然发现这篇文章的人:hamcrest 2.0 引入了一个新的匹配器:
matchesPattern
来匹配正则表达式模式。以下代码应该可以工作:Dependency:
...
...
注意:
{
和}
是 java 中的正则表达式字符,因此必须在匹配器字符串中转义。For anyone stumbling onto this post like me: hamcrest 2.0 has introduced a new matcher:
matchesPattern
to match a regex pattern. The following code should work:Dependency:
...
...
Note:
{
and}
are regex characters in java so must be escaped in the matcher string.