Frage

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' : '[]'
War es hilfreich?

Lösung

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)

Andere Tipps

For those coming to this question looking for an answer, the answer supplied by Eric is no longer valid.

It seems the current way (specs2 3.8) to match an empty array would be:

json must /("roles").andHave(exactly[String]())

This is not the best way, but it's the only one I found that works and makes some sense when read back.

The andHave matches against the contents of roles and exactly with no parameters matches an empty array. The use of the String type parameter is there because otherwise the compiler complains it can't infer the type.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top