Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to assert values of a JSON array? #26

Open
wimdeblauwe opened this issue Sep 20, 2018 · 4 comments
Open

How to assert values of a JSON array? #26

wimdeblauwe opened this issue Sep 20, 2018 · 4 comments

Comments

@wimdeblauwe
Copy link

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
Copy link
Member

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

@wimdeblauwe
Copy link
Author

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

@dennisdoomen
Copy link
Member

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

@wimdeblauwe
Copy link
Author

wimdeblauwe commented Sep 20, 2018

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");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants