Hamcrest matcher for a String, where the String contains some random values
Asked Answered
S

3

5

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}")))
Samora answered 21/12, 2011 at 10:17 Comment(1)
That would be better written allOf(startsWith("..."), endsWith("...")).Expanded
M
5

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() and endsWith() with allOf().

Membranophone answered 21/12, 2011 at 10:28 Comment(0)
G
3

It looks like JSON. Why not use a JSON parser?

Gynecologist answered 24/12, 2011 at 1:27 Comment(0)
U
2

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:

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\\}")
);

Note: { and } are regex characters in java so must be escaped in the matcher string.

Uptown answered 15/3, 2019 at 11:29 Comment(1)
There's also matchesRegex. It's unclear what the difference is.Zonation

© 2022 - 2024 — McMap. All rights reserved.