【问题标题】:How to handle an variable that returns null inside an Assert如何处理在 Assert 中返回 null 的变量
【发布时间】:2019-11-16 02:29:10
【问题描述】:

我忙于使用 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 匹配 type 断言正在传递 (true)。

如果var org = null,我希望 Assert 返回 false,并带有消息 - Failed type

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

关于如何处理的任何想法?

提前致谢。

【问题讨论】:

  • org != null &amp;&amp; org.applicationType 将空 org 设为 false 并确保在 org 为空时不评估 org.applicationType

标签: c# selenium restsharp


【解决方案1】:

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

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

org?.applicationTypenull 如果 org 为空,因此这将解决引发的异常。该语句断言org?.applicationType == type,因此当orgnull 时,比较将是null == type。这将返回 false,因此如果 org.applicationType 为 null,则测试失败,如果 org.applicationType == type 则通过。

【讨论】:

  • 是的。现在它处理空值。但不幸的是,如果断言为真,它也会返回失败消息:|
  • 你也可以Assert.IsNotNull(org?.applicationType);。但这实际上并没有检查type。我认为你应该使用Assert.IsTrue(org?.applicationType == type);——我更新了我的答案和解释。
  • @Christina。是的真棒。现在它可以工作了,非常感谢。这 ?语法对我很有帮助:D
猜你喜欢
  • 1970-01-01
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-07
  • 1970-01-01
  • 2020-06-29
相关资源
最近更新 更多