drobert drobert - 5 months ago 26
JSON Question

Specs2 JsonMatchers match 'empty array'

I have the following json string:

{"guid": "4bad1d9a-180f-4751-a698-4aac07b1eac7","partition":1,"roles": []}


I've been able to use specs2's org.specs2.matcher.JsonMatchers to enforce guid and partition, e.g.:

json must /("guid" -> "4bad1d9a-180f-4751-a698-4aac07b1eac7")
json must /("partition" -> 1)


But I cannot figure out the correct syntax to enforce that 'roles' is present and 'is an empty array'. Is this do-able?

Edit:

Per a commenter's question, I have tried the following:

json must /("roles" -> "[]")


which results in the following test failure:

[error] {guid : 5ad4c4c5-4fdb-461b-9883-b84ff3b84610,partition : 1.0,roles : []} doesn't contain 'roles' : '[]'

Answer

The value to be tested for roles is of scala.util.parsing.json.JSONArray type so you can write:

json must /("roles" -> JSONArray(Nil))

And if that comes up a lot maybe define a value:

val empty = JSONArray(Nil)
json must /("roles" -> empty)