简体   繁体   中英

Creating reusable method with variable conditional logic

I have several variations of the following code within methods that are being used for Selenium testing (waits for certain events before returning) and I would like to refactor it and make it reusable so I have the logic controlling the delay & try/catch as a generic method but be able to swap in and out conditions depending on situation.

Is there an easy way to achieve this?

Code:

for (int second = 0; second <= 10; second++)
    {
            try
            {
                // bit that needs to vary
                matchedAddresses = driver.FindElements(By.ClassName("addresslookup"));
                if (matchedAddresses.Count > 0)
                {
                    break;
                }

            }
            catch (Exception)
            {
            }
            Thread.Sleep(1000);
        }          
return matchedAddresses.Count;

You want function that takes argument of something like Func<int> - method that returns number of elements (or enumerable Func<IEnumerable<sometype>> )

public int GetCountOfElementsWithWait(Func<int> test)
{
    .....
    var count = test();
    ....
}

Seems a bit too obvious, but would this work?

public int GetCountOfElementsByClassName(string className)
{
    for (int second = 0; second <= 10; second++)
    {
        try
        {
            // bit that needs to vary
            matchedElements = driver.FindElements(By.ClassName(className));
            if (matchedElements.Count > 0)
            {
                break;
            }

        }
        catch (Exception)
        {
        }
        Thread.Sleep(1000);
    }          
    return matchedElements.Count;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM