Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodedUI - Check if a control exists or not

I have a web page with a login button, to get to the site you simply click the button. This is easily done by writing this:

//Click the Login button

        UITestControl Login = new UITestControl(Browser);
        Login.TechnologyName = "Web";
        Login.SearchProperties.Add("ControlType", "Button");
        Login.SearchProperties.Add("Type", "Submit");
        Login.SearchProperties.Add("DisplayText", "Log In");
        Mouse.Click(Login);

HOWEVER, after you login the first time, you remain logged in for an hour (auto log out if idle for over an hour). If you access the site more than once within an hour, there will be no login button since you are still logged in so everytime I run my test, it will error right away because it won't find the control.

I hope that makes sense, here is a synopsis:

First time to site - Login screen appears, click login button, gain entry Subsequent times to site - No login screen appears,no login required

so basically I want to say, "If there is a login button, click it then do the next thing, if no login button, then do the next thing"

like image 931
Rob W Avatar asked Mar 05 '26 05:03

Rob W


1 Answers

There is a TryFind() method which you can use.

 UITestControl Login = new UITestControl(Browser);
 Login.TechnologyName = "Web";
 Login.SearchProperties.Add("ControlType", "Button");
 Login.SearchProperties.Add("Type", "Submit");
 Login.SearchProperties.Add("DisplayText", "Log In");

 // TryFind() returns true if it's in the Markup somewhere, even if hidden.
 // By testing Width > 0 && Height > 0, we make sure it is visible.
 // If it were Hidden and we did not use TryFind() before checking Height
 // or Width, there would be an exception thrown.
 if(Login.TryFind() && Login.Width > 0 && Login.Height > 0)
 {
      Mouse.Click(Login);
 }

There is also the TryGetClickablePoint method that you can use instead of looking for width and height.

 Point p;
 if(Login.TryGetClickablePoint(out p))
 {
      Mouse.Click(Login);
 }
like image 95
MPavlak Avatar answered Mar 08 '26 20:03

MPavlak