fluentassertions / fluentassertions.json

NewtonSoft.Json extensions for FluentAssertions
Apache License 2.0
72 stars 26 forks source link

`ContainSubtree` constraint #6

Closed BalassaMarton closed 6 years ago

BalassaMarton commented 7 years ago

This constraint will match a JSON document against a subtree. This is useful when verifying JSON data, and multiple but not all properties of an object must be compared against known values. Example: I am testing some CRUD web service, have a response like this:

{
  success: true,
  data: {
    id: 123,
    name: 'Foo',
    type: 'my-type',
    someOtherProperty: 'asd'
  }
}

...and I want to assert that the request succeeded and the returned object has type my-type with name Foo. The other properties are irrelevant and/or unknown. Without this assertion, I'd have to write something like this:

response["success"].Should().HaveValue(true);
response["data"]["type"].Should().HaveValue("my-type");
response["data"]["name"].Should().HaveValue("Foo");

Yuck! The same test can be done with a single call using ContainSubtree:

response.Should().ContainSubtree(JToken.Parse(" { success: true, data: { type: 'my-type', name: 'Foo' }  } "));

When using with arrays, the assertion is that the JSON array under testing must contain a matching element for each of the elements in the subtree array, eg. this should fail:

var json = JToken.Parse("[ { name: 'Alpha' }, { name: 'Bravo' }, { name: 'Charlie' } ]");
json.Should().ContainSubtree(JToken.Parse("[ { name: 'Alpha' }, { name: 'Delta' } ]"));
dennisdoomen commented 6 years ago

Sorry, I missed this PR. Would you be willing to rebase on the release-5.0 hot-fix branch?

BalassaMarton commented 6 years ago

Hi, sure, as soon as I learn how to do that :)

dennisdoomen commented 6 years ago

https://www.atlassian.com/git/tutorials/rewriting-history/git-rebase :-)

BalassaMarton commented 6 years ago

I did a rebase althouth I'm not sure it worked. Can you look at it? I also commited the nuspec, please ignore it when merging.

dennisdoomen commented 6 years ago

Apparently you forgot to change the target branch to release 5.0. I didn't see that and accidentally merged this change. I'm currently merging 5.0 to master, so I'll ping you to re-apply the change later on