"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:
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.