Coded UI Control.Exists. System.NullReferenceExcep

2019-03-01 22:28发布

I want to check that window exists after some actions. I try:

 protected override Boolean IsPresent()
    {
        if (_mainWindow == null)
        {
            _mainWindow = new WinWindow();
            _mainWindow.SearchProperties[WinWindow.PropertyNames.ControlName] = "MainWindow";
        }
        return _mainWindow.Exists;
    }

But if control does not exist mainWindow.Exists throws System.NullReferenceException. I can't understand why it happens because mainWindow reference in this code can't be null. How can I verify is _mainWindow founded or not?

I've did it to wait for window loading with timeout. I've also tried to use MainWindow.FindMainWindow().WaitForControlExist(100000) but it doesn’t wait needed timeout. This code also not set my needed timout:

Playback.PlaybackSettings.SearchTimeout = 100000;
Playback.PlaybackSettings.WaitForReadyTimeout = 100000;

I use VS2013.

UPD:

This is my code with NRE check:

protected override Boolean IsPresent()
{
    if (_mainWindow == null)
    {
        _mainWindow = new WinWindow();
        _mainWindow.SearchProperties[WinWindow.PropertyNames.ControlName] = "MainWindow";
    }
    try
    {
        return _mainWindow.TryFind(); //TODO WTF?
    }
    catch (NullReferenceException e)
    {
        Console.WriteLine("We've got a NullReferenceException");
        Console.WriteLine("_mainWindow reference is " + ((_mainWindow == null) ? "NULL" : "NOT NULL"));
        throw e;  //Line 41
    }
}

And this is the result:

We've got a NullReferenceException
_mainWindow reference is NOT NULL
Attachments:

file:///Project/TestResults/User_WIN-FP7FMM7PUB1%202017-04-09%2015_57_34/In/4acd6ac8-92ce-4746-8787-3aecfd63bdd8/WIN-FP7FMM7PUB1/SuccessLoginTest.png

Test method UITest.AutoTests.LoginTests.SuccessLoginTest threw exception: 

System.NullReferenceException: object reference not set to an instance of an object.
   in UITest.Locators.MainWindow.IsPresent() in MainWindow.cs: line 41
   in UITest.Locators.BaseWindow.Wait() in BaseWindow.cs: line 34
   in UITest.Locators.MainWindow..ctor() in MainWindow.cs: line 18
   in UITest.Locators.LoginWindow.ClickEnterButton() in LoginWindow.cs: line 57
   in UITest.AutoTests.LoginTests.SuccessLoginTest() in LoginTests.cs: line 32

2条回答
聊天终结者
2楼-- · 2019-03-01 22:38

The problem was in version of VS2013. I have installed Update 5 and now TryFind() returns False if object not found.

查看更多
何必那么认真
3楼-- · 2019-03-01 22:56

Exists is not what you want to use. You can use TryFind() instead.

 protected override Boolean IsPresent()
 {
     if (_mainWindow == null)
     {
         _mainWindow = new WinWindow();
         _mainWindow.SearchProperties[WinWindow.PropertyNames.ControlName] = "MainWindow";
     }
     return _mainWindow.TryFind();
 }

For more examples of how to use Coded UI to do various tasks, see my website codeduiexamples.com

查看更多
登录 后发表回答