有没有更好的方法来测试NullReferenceException?

时间:2014-07-10 14:17:12

标签: c# visual-studio-2010 nullreferenceexception coded-ui-tests

应用程序正在运行,应用程序的窗口在屏幕上可见, 但编码的ui测试总是得到一个NullReferenceException:

  • sampling = application
  • sampling.Window =应用程序的主窗口

代码:

if(object.ReferenceEquals(sampling, null)) // sampling is not a null reference (debug output)
if(sampling == null) //  sampling is not null
if(object.ReferenceEquals(sampling.Window, null)) //  sampling.Window is not a null reference
if(sampling.Window == null) //  sampling.Window is not null
if (sampling.Window.Exists) //  sampling.Window exists? True
if(sampling.Window.TryGetClickablePoint(out pt)) //  Got clickable point? False  Point = {X=0,Y=0}

if(object.ReferenceEquals(sampling.Window.BoundingRectangle, null)) //  Exception: object reference not set to an instance of an object.
if(object.ReferenceEquals(sampling.Window.ControlType, null)) //  Exception: object reference not set to an instance of an object.
if(object.ReferenceEquals(sampling.Window.Name, null)) //  Exception: object reference not set to an instance of an object.
if(object.ReferenceEquals(sampling.Window.ClassName, null)) //  Exception: object reference not set to an instance of an object.
if(sampling.Window.BoundingRectangle == null) //   Exception: object reference not set to an instance of an object.
if(sampling.Window.ControlType == null) //   Exception: object reference not set to an instance of an object.
if(sampling.Window.Name == null) //   Exception: object reference not set to an instance of an object.
if(sampling.Window.ClassName == null) //   Exception: object reference not set to an instance of an object.

1 个答案:

答案 0 :(得分:0)

如果sampling.Window本身 null,但sampling.Window.Name == null之类的内容会导致NullReferenceException,我怀疑该异常来自于属性get的{​​{1}}访问者。

您是否在没有优化的情况下编译了这个(在" Debug"模式下)并尝试使用附加的Visual Studio调试器运行它?它应该在异常发生时暂停执行,你应该能够看到哪个引用是Name。它可能位于Visual Studio高亮显示的行上方。