Skip to content
Hamcrest matchers for JSON objects
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
.0pdd.yml
.gitignore
.pdd.yml
.rultor.yml
.travis.yml
LICENSE
README.md
pom.xml

README.md

matchers-json

Hamcrest matchers for json objects

EO principles respected here DevOps By Rultor.com

Bintray Build Status Build status PDD status License Test Coverage

Get

To install it add dependency to your pom.xml:

<dependency>
  <groupId>com.g4s8</groupId>
  <artifactId>matchers-json</artifactId>
  <version></version>
</dependency>

you can find latest version on Bintray badge above.

Usage

Matching JSON objects

To match any field in JSON object use JsonHas:

MatcherAssert.assertThat(
    Json.createObjectBuilder()
        .add(
            "foo",
            Json.createObjectBuilder()
              .add("bar", 42)
              .build()
        ).build(),
    new JsonHas(
        "foo",
        new JsonHas(
            "bar",
            new JsonValueIs(42)
        )
    )
);

Matching JSON arrays

To match JSON array use JsonContains class with list of matchers for items as argument:

new JsonContains(
    new JsonValueIs("foo"),
    new JsonValueIs(42),
    new JsonValueIs(true),
    JsonValueIs.NULL
)

Also you can use JsonHas matcher to match JSON objects in array:

new JsonContains(
    new JsonHas("value", new JsonValueIs(1234)),
    new JsonHas("value", new JsonValueIs(6532))
)

or use JsonContains as JsonHas argument to match an array in JSON object field:

new JsonHas(
    "items",
    new JsonContains(
        new JsonValueIs(1),
        new JsonValueIs(2),
        new JsonValueIs(3)
    )
)

Matching JSON values

To match json value use JsonValueIs:

For strings: new JsonValueIs("some string")

For numbers: new JsonValueIs(100)

For booleans: new JsonValueIs(true)

For json-null: JsonValueIs.NULL

For more complex matching you can use primary constructor:

MatcherAssert.assertThat(
    Json.createValue("Starting with 1 2 3"),
    new JsonValueIs(
        JsonValue.ValueType.STRING,
        Matchers.startsWith("Starting")
    )
);

Additional

Also this library provides some useful classes to help you convert different types to JSON matchers:

StringIsJson is decorator for JSON matcher which implements Matcher<String> interface, so you can match a string against JSON matchers:

MatcherAssert.assertThat(
    "{\"foo\":\"bar\"}",
    new StringIsJson(new JsonHas("foo", new JsonValueIs("bar")))
);

Contribution

  1. Fork the repo
  2. Make changes
  3. Run mvn clean install -Pqulice
  4. Submit a pull request

Keep in mind that PR will not be accepted if it doesn't pass unit tests and Qulice checks.

If something is not clear to you or documentation is missed, please submit a bug.

If something is not working, please submit a bug.

You can’t perform that action at this time.