0
"packages": [
           {
             "TriggerType": "sample",
             "StatusDescription": "",
             "Score": null,
             "Percentile": null,
             "Band": ""
           }
         ]

When I parse this JSON using JObject attachmentData = JObject.Parse(targetPayload);

and perform the unit testing.


Assert.AreEqual("", attachmentData.SelectToken("packages")[0].SelectToken("Score").ToString());

This works fine but I want to check


Assert.AreEqual(null, attachmentData.SelectToken("packages")[0].SelectToken("Score").ToString());

or 
Assert.IsNull(attachmentData.SelectToken("packages")[0].SelectToken("Score").ToString());

These are giving the following errors.


Assert.AreEqual failed. Expected:<(null)>. Actual:<>

{"Assert.IsNull failed. "}


Thanks!

1 Answers1

2

You can use JToken's Value or HasValue:

var score = o.SelectToken("packages")[0].SelectToken("Score");

// score.Value is null
// score.IsValue is false

In your test:

Assert.AreEqual(null, attachmentData.SelectToken("packages")[0].SelectToken("Score").Value);

Please note that if there is no score (or packages) this will throw and you may want:

Assert.AreEqual(null, attachmentData.SelectToken("packages")?[0]?.SelectToken("Score")?.Value);

This depends what you are trying to check:

  1. Score is there but the value is null
  2. Just to ensure that there is no score (so null or lack of presence are both OK
  3. Something else.

I want to check the score is there and value is null

var score = attachmentData.SelectToken("packages")?[0]?.SelectToken("Score");
Assert.IsNotNull(score);
Assert.IsFalse(score.Value<string>());

Or

Assert.IsNotNull(score);
var v = (JValue)score;
Assert.IsNull(v.Value);
tymtam
  • 31,798
  • 8
  • 86
  • 126
  • Thanks! but I need this to work and can you this type of assertion Assert.AreEqual(null, attachmentData.SelectToken("packages")[0].SelectToken("Score").ToString()); – Srikrishna Sharma Apr 29 '21 at 02:17
  • I want to check the score is there and value is null – Srikrishna Sharma Apr 29 '21 at 02:26
  • Tried using this but doesnt work for me var score = attachmentData.SelectToken("packages")[0].SelectToken("Score"); Assert.IsNotNull(score); Assert.IsNull(score.Values()); – Srikrishna Sharma Apr 29 '21 at 02:32
  • This means that when i tried using the code above it doesnt work and giving the same error every time. Assert.IsNull(score.Value); this is giving compile error and Assert.IsNull(score.Values()) and this fails – Srikrishna Sharma Apr 29 '21 at 02:36
  • 1
    @SrikrishnaSharma Sorry I updated the code. I think `score.Value()` is your best option. – tymtam Apr 29 '21 at 02:41
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/231720/discussion-between-srikrishna-sharma-and-tymtam). – Srikrishna Sharma Apr 29 '21 at 02:43
  • Assert.AreEqual(null, attachmentData.SelectToken("packages")[0].SelectToken("Percentile").Value()); – Srikrishna Sharma Apr 29 '21 at 02:50