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}")))
1
  • That would be better written allOf(startsWith("..."), endsWith("...")). Dec 24, 2011 at 5:13

3 Answers 3

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().

3

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

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.