fluentassertions / fluentassertions.json

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

How to assert values of a JSON array? #26

Open wimdeblauwe opened 6 years ago

wimdeblauwe commented 6 years ago

I am trying out fluentassertions.json and I wonder how I can assert values in a json array. Suppose I have a controller that returns:

["value1","value2"]

And the following test:

var response = await client.GetAsync("/api/values");

response.EnsureSuccessStatusCode();

Assert.Equal(HttpStatusCode.OK, response.StatusCode);
response.StatusCode.Should().Be(HttpStatusCode.OK);
response.Content.Headers.ContentType.ToString().Should().Be("application/json; charset=utf-8");
var json = await response.Content.ReadAsStringAsync();
_output.WriteLine(json);
JToken.Parse(json).Should().HaveCount(2);

So far, so good. Now I would like to write something like this:

JToken.Parse(json).Should().HaveCount(2).And.HaveValue("value1").And.HaveValue("value2");

Is there a way to do this?

dennisdoomen commented 6 years ago

The JSON API is pretty limited right now, so I don't think you have many options there.

wimdeblauwe commented 6 years ago

Are there plans to add support for Jsonpath (https://www.newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm) ?

dennisdoomen commented 6 years ago

No. My focus is mostly on the main library. But we're open to PRs 😉

wimdeblauwe commented 6 years ago

This is my 2nd day doing .NET development, so a PR is a bit of a stretch for now :-)

But I managed to get what I needed manually like this:

JToken.Parse(json).Should().HaveCount(2);
JToken.Parse(json).SelectToken("$[0]").Value<string>().Should().Be("value1");
JToken.Parse(json).SelectToken("$[1]").Value<string>().Should().Be("value2");

or:

JToken.Parse(json).SelectTokens("$").Values<string>().Should()
    .HaveCount(2)
    .And.Equal("value1", "value2");