如何处理断言中 returns null 的变量

How to handle an variable that returns null inside an Assert

我忙于使用 selenium 并且在使用 Assert 时遇到了一些困难。 我有这样的东西。

_request = new RestRequest($"applications", Method.GET);
var result = JsonConvert.DeserializeObject<AppRoot[]>(_restClient.Execute(_request).Content);

var org = result.FirstOrDefault(a => a.orgNr.ToString() == "1337");

Assert.IsTrue((org.applicationType == type && org == null) ? true : false, "Failed" + type);

现在如果 org.applicationType 匹配 类型 断言通过(真)。

如果 var org = null,我希望断言为 return false,并显示消息 - Failed type

但是这里的断言正在寻找变量并且失败了经典 System.NullReferenceException : 对象引用未设置到实例

关于如何处理这个问题有什么想法吗?

提前致谢。

我认为 ? conditional access 语法将帮助您避免错误消息。这将处理 org 为空的情况:

Assert.IsTrue(org?.applicationType == type, "Failed" + type);
如果

org?.applicationTypenull,则 org 为空,因此这将解决抛出的异常。此语句断言 org?.applicationType == type,因此当 orgnull 时,比较将为 null == type。此 returns 为假,因此如果 org.applicationType 为空则测试失败,如果 org.applicationType == type.

则通过测试