Hamcrest matcher for a String, where the String contains some random values
Question
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}")))
Solution
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()
.
OTHER TIPS
It looks like JSON. Why not use a JSON parser?
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.