Asparuh Ivanov
Asparuh Ivanov

Reputation: 41

Can I use System.Timers as an alternative to Thread.Sleep() when testing with C# and Selenium in Visual Studio 2019?

I am trying to replace all (or at least most) the Thread.Sleep() in my tests and it seems System.Timers can do the work but I don't know how to implement it.

Or if you guys know another replacement please let me know.

I would really appreciate it if somebody helps me here.

Thank you.

Edit: Sorry, it's my first question here, I should have given an example:

public void AdditionalCardIssueNoBankBranchSelected()
    {
        
        additionalCardApplicationPage.ClearBankConsultantCodeField();
        additionalCardApplicationPage.TypeSalesOfficer();
        additionalCardApplicationPage.TypeEIKBankCustomerAndPressGetDataButton();
        additionalCardApplicationPage.ChooseMainCard();
        chooseMainCardPage.TypeCustomerEikAndPressSearchButton();
        Thread.Sleep(1000);
        bankCardSearchPage.SelectFirstValidBankCardOther();
        chooseMainCardPage.PressChooseMainCardButton();
        additionalCardApplicationPage.PressStartApplicationButton();
        Thread.Sleep(1000);
        IAlert alert = driver.SwitchTo().Alert();
        alert.Accept();
        Assert.IsTrue(additionalCardApplicationPage.BankBranchCodeAlert.Displayed);
    }

So pretty much everywhere I have Thread.Sleep() is because I am waiting for the page to load in full because if it doesn't next action will not happen as the element I want to interact with is not visible yet. Sometimes bankCardSearchPage.SelectFirstValidBankCardOther() will not go thru because the table where the cards are is not visible yet.

I hope I explained it well. Thank you.

Upvotes: 1

Views: 128

Answers (1)

cruisepandey
cruisepandey

Reputation: 29362

Thread.sleep()

is an explicit wait but worst of it's kind.

best one is below (Explicit wait):

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//span[text()='OK']/..")));

You can pretty much replace everything with the dynamic wait mentioned above.

What it would do is that to look for web element in DOM for every 500ms until 20 seconds (as we have defined 20 in the above object creation), if found it would return the web element, if not a Timeout exception will be raised.

Upvotes: 4

Related Questions