2011-12-21 102 views
3

有沒有辦法將以下字符串與任何hamcrest匹配器進行匹配。Hamcrest匹配器的字符串,其中字符串包含一些隨機值

"{\"messageType\":\"identify\",\"_id\":\"7de9a446-2ced-4bda-af35-81e95ad2dc32\",\"address\":\"192.168.0.0\",\"port\":7070}" 

該字符串被傳遞給一個方法。我使用JMock期望來匹配它。

問題:「72e3a446-2fed-4bda-ac35-34e95ab3dc32」部分是隨機生成的UUID,它是在測試方法內部生成的。是否有一個Hamcrest字符串匹配將匹配類似

new StringCompositeMatcher("{\"messageType\":\"identify\",\"_id\":\"", with(any(String.class)), "\"address\":\"192.168.0.0\",\"port\":7070}") 

它必須與預期的字符串"{\"messageType\":\"identify\",\"_id\":\"開始出現後,任何字符串,並與",\"address\":\"192.168.0.0\",\"port\":7070}"

編輯結束:該解決方案

with(allOf(new StringStartsWith("{\"messageType\":\"identify\",\"_id\":\""), new StringEndsWith("\",\"address\":\"192.168.0.0\",\"port\":7070}"))) 
+0

這將是更好的寫作'allOf(startsWith( 「... 」),的endsWith(「 ...」))'。 – 2011-12-24 05:13:33

回答

3

也許最優雅的方法是使用正則表達式,儘管沒有內置的匹配器。但是,you can easily write your own

或者,您可以將startsWith()endsWith()allOf()結合使用。

3

它看起來像JSON。爲什麼不使用JSON解析器?

相關問題