Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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}")))
like image 282
Kiril Kirilov Avatar asked Jan 18 '23 00:01

Kiril Kirilov


1 Answers

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

like image 96
axtavt Avatar answered Jan 30 '23 14:01

axtavt