简体   繁体   中英

Test Cases Fail On Null Assertion

"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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM