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

fiction picture fiction · Dec 21, 2011 · Viewed 7.5k times · Source

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

Answer

axtavt picture axtavt · Dec 21, 2011

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