martin-helmich/phpunit-json-assert

Testing that an attribute does not exist

denisvmedia opened this issue · 1 comments

First of all, let me thank you for your library. I find it really useful in testing JSON APIs. However, I think I faced a problem that I'm not sure how to work around.

So, we have this json:

{
  "@context": "/api/contexts/Book",
  "@id": "/api/books",
  "@type": "hydra:Collection",
  "hydra:member": [
    {
      "@id": "/api/books/1",
      "@type": "Book",
      "id": 1,
      "name": "Oxford English Dictionary"
    },
    {
      "@id": "/api/books/2",
      "@type": "Book",
      "id": 2,
      "name": "The Hitchhiker's Guide to the Galaxy",
      "bookshelf": "/api/bookshelves/1"
    }
  ],
  "hydra:totalItems": 2
}

Now I want to test that the first item does not have a bookshelf element. In fact, in json it simply means null. But testing on null (as well as on empty) fails. What I tried:

  1. self::assertJsonValueEquals($content, '$["hydra:member"][0]["bookshelf"]', null);
  2. self::assertJsonValueMatches($content, '$["hydra:member"][0]["bookshelf"]', PHPUnit\Framework\Assert::isEmpty());
  3. self::assertJsonValueMatches($content, '$["hydra:member"][0]["bookshelf"]', PHPUnit\Framework\Assert::isNull());

But any of those unfortunately fail to match. Is there a way to do that? Thanks!

This is, by the way, a workaround:

    $bookshelfIdData = (new JSONPath(json_decode($content, true)))
        ->find('$["hydra:member"][0]["bookshelf"]')->getData();
    self::assertArrayNotHasKey(0, $bookshelfIdData);