如何应用等待策略以防它始终不起作用?

问题描述 投票:0回答:1

我们在等待上遇到了间歇性失败,尽管我们已经在启动 url 时应用了隐式等待、流畅等待和显式等待一些元素,甚至我们也使用了 thread.sleep 函数以及有几个地方其他 3 个(selenium //waits)不起作用。

We are having intermittent failures on the waits, although we have already applied, implicit //wait when we launch the url, fluent wait, and explicit wait for a few elements and even we //have used thread.sleep function as well as a couple of places where the other 3 (selenium //waits) don't work.
//When an element loads slowly, especially for asserting alert pop-up message validations?
`//Case 1:-> For implicit wait 
//below code launch the application.**your text**
public class BrowserOperations
{
    WebDriver driver;


    public WebDriver LaunchApplication(String browserName) throws Exception
    {   
        System.out.println("Browser \""+browserName+"\"");
        switch(browserName)
        {
        case "Chrome":
            
            DesiredCapabilities jsCapabilities = new DesiredCapabilities();
            ChromeOptions chromeOptions = new ChromeOptions();
            //chromeOptions.addArguments("--remote-allow-origins=*");
            //chromeOptions.addArguments("--incognito");
            Map<String, Object> prefs = new HashMap<>();
            prefs.put("intl.accept_languages", "en-US");
            chromeOptions.setExperimentalOption("prefs", prefs);
            jsCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
            
                        
            Map<String, Object> prefsMap = new HashMap<String, Object>();
              prefsMap.put("profile.default_content_settings.popups", 0);
              prefsMap.put("download.default_directory", PropertiesfileDataProvider.GetPropertyValue("DownloadPath"));

            chromeOptions.setExperimentalOption("prefs", prefsMap);
            // need to uncomment below line for headless option
            if(PropertiesfileDataProvider.GetPropertyValue("headless").equals("Yes")) {
                chromeOptions.addArguments("--headless=new");
                System.out.println("With headless browser");
            }else
                System.out.println("No headless browser");
            
            driver=new ChromeDriver(chromeOptions); 
            
            break;


driver.manage().window().maximize();
        
          System.out.println(driver.manage().window().getSize());
          driver.manage().window().setSize(new Dimension(1440, 1024));
          System.out.println(driver.manage().window().getSize());
         
         System.out.println("URL: "+PropertiesfileDataProvider.GetPropertyValue("URL"));
        driver.get(PropertiesfileDataProvider.GetPropertyValue("URL"));
        
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(60));
        return driver; 

//Case 2:-> explicit wait 
//example login detail function through which user enters the details and enter to application
public void enterLoginDetails(String username, String password) throws InterruptedException {
        WebDriverWait wait=new WebDriverWait(driver,Duration.ofSeconds(240));
        wait.until(ExpectedConditions.elementToBeClickable(textbox_Username));
        textbox_Username.sendKeys(username);
        textbox_Password.sendKeys(password);
        button_Login.click();
        BaseClass.logger.info("Logged in to application");
        System.out.println("Logged in to application");
        selectInterfaceLanguage();
    }


//case 2:-> fluent wait 
//Below is the fluentwait which is written to handle different conditions 
public void fluentwaitWithExpectedCondition(String expectedCondition, WebElement element) {

        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(Duration.ofSeconds(180))
                .pollingEvery(Duration.ofSeconds(5)).ignoring(NoSuchElementException.class);
//Below are the conditions on which element will be actions
        switch (expectedCondition) {
        case "clickable":
            wait.until(ExpectedConditions.elementToBeClickable(element));
            break;
        case "visible":
            wait.until(ExpectedConditions.visibilityOf(element));
            break;
        case "stateToBe":
            wait.until(ExpectedConditions.elementSelectionStateToBe(element, false));
            break;
        case "invisible":
            wait.until(ExpectedConditions.invisibilityOf(element));
            break;
        default:
            wait.until(ExpectedConditions.visibilityOf(element));
        }

    }

//below is my test script

@Test

public void testcaseaut() 
{
        try {
            
            LoginWithUser();//Login function which uses browser operation class to launch the url for specific browsers.
            if (driver.getCurrentUrl().contains(env1) ||           driver.getCurrentUrl().contains(env2)) 
            { 
            NavigateTofeature(); // funtion to navigate to feature which is written in the same class
            createAndDeleteUser("Ramana", "xuz", "[email protected]");// function to create user
            featurePageObj.clickOnfeaturefMenu();
            featureOBJ.clickOnUserdownloadInfoFromaddfeatureMenu();
            Thread.sleep(5000);
            Assert.assertTrue(featureOBJ.VerifyUserIsPresentOndownloadInFoPopUp("ramanaaddfeature@[email protected]"));
            Thread.sleep(500);
            featureOBJ.checkboxSelectAllPresentOndownloadUserInfoPopUp();
            Thread.sleep(500);
            featureOBJ.clickdownloadButtonOndownloadUsersInfoPopup();
            featureOBJ.clickYesButtonOnConfirmAction();
            logger.pass("User clicked on yes button for confirm action popup");
            Thread.sleep(1000);
            featureOBJ.clickviewJobLogsButtonOnJobStatusPopUp();
            logger.pass("User clicked on view job logs button for job status popup");
            Thread.sleep(7000);
            applyFilterForUserOnLogScreenForJobTypeUserInfodownload();
            Thread.sleep(5000);
            logScreenForJobTypeUserInfodownloadAndClickOnDisplayLogForFirstRow();
            infoMessageOnMessageTabForUserInfodownload();
            infoMessageOnFilesTabForUserInfodownload();
            jobLogObj = new addfeatureUserJobLog(driver);
            String dateVar=jobLogObj.returnDateFieldInFormatFromFilesDisplayLogForUserdownloadLikeDisplayedOnlocaiInfoPopUp();
                        clickOndirectoryAndSelectWorkspaceThanNavigateTorequired();
            featureOBJ = new requiredPage(driver);
            featureOBJ.VerifyrequiredPage();
            //driver.navigate().refresh();
            Thread.sleep(5000);
            featureOBJ.clickOnaddfeatureMenu();
            Thread.sleep(3000);
            featureOBJ.clickOnUserprocess();
            Thread.sleep(5000);
            //test case steps to verify that recovery date displayed for a user that is deleted and downloaded
            featureOBJ.clickAndSendValueToSearchFieldOnlocaiUsersInfoPopup("ramanaaddfeature@[email protected]");
            Thread.sleep(2000);
            //jobLogObj = new addfeatureUserJobLog(driver);
            jobLogObj.verifyenddateDateIsDisplayedOnlocaiUserInfoPopUp(dateVar);
            jobLogObj.clickOnCancelButton();
            Thread.sleep(2000);
            createAndDeleteUser("Bamana", "addfeature", "bamanaaddfeature@[email protected]");
            featureOBJ.clickOnaddfeatureMenu();
            Thread.sleep(3000);
            featureOBJ.clickOnUserprocess();
            Thread.sleep(5000);
            //test case steps to verify that recovery date should displayed for a user that is deleted and downloaded
            featureOBJ.clickAndSendValueToSearchFieldOnlocaiUsersInfoPopup("bamanaaddfeature@[email protected]");
            Thread.sleep(2000);
            //verifyenddateDate
            jobLogObj.verifyenddateDateNotDisplayedOnlocaiUserInfoPopUp(dateVar);

            }
            else 
            {
                System.out.println("Not applicable for remaining urls");
            }
          
            
        } catch (AssertionError error) {
            logger.fail(error.getMessage());
            logger.fail(ExceptionUtils.getStackTrace(error));
            Assert.fail(ExceptionUtils.getStackTrace(error));
        } catch (Exception exception) {
            System.out.println("Catch Block");
            logger.fail(exception.getMessage());
            logger.fail(ExceptionUtils.getStackTrace(exception));
            Assert.fail(ExceptionUtils.getStackTrace(exception));
        }
}`

上面的代码正在尝试运行脚本“testcaseaut”

--

type here

”,具有一些支持功能,在上面的代码中给出。 并解释了代码。 我们试图问为什么等待策略不起作用。

java maven selenium-webdriver sapui5 webdriverwait
1个回答
0
投票

感谢您的回复, 我尝试从代码中删除隐式,并仅使用显式等待来运行脚本,无论是可见条件还是持续时间为 120 秒的可点击条件

但我的测试间歇性失败(比如五次、两次在我明确等待的同一位置失败),但如果我应用 Thread.sleep 几秒钟,它就会起作用。

public void ClickWorkspace() throws Exception
{
   commonFunctionsObj.WaitUntilTextToBePresentInElement( workSpace, "some 
     text");
    String 
 workspace=commonFunctionsObj.GetWorkspaceAccordingtoEnvironment();
//Required the changes as per the number of workspace increased and with 
the below code 
//we can filter the required workspace and perform operations
workspace_Header.click();//clicking on the column name workspace which will 
open a filter (input box)
BaseClass.logger.pass("Clicked on filter by workspace");
System.out.println("Clicked on filter by workspace");
WebElement eleFilter = driver.findElement(By.xpath("//input[@class='class1 
class2']"));

try {
    eleFilter.isDisplayed();
} catch (NoSuchElementException ex) {
    BaseClass.logger.info("Not clicked retrying.........");
    workspace_Header.click();
}
 // Thread.sleep(2700);
 commonFunctionsObj.WaitUntilVisibilityOfElement(eleFilter);
 commonFunctionsObj.WaitUntilElementIsClickable(eleFilter);
 eleFilter.sendKeys("="+workspace);//giving value to filter box
 driver.findElement(By.xpath("//input[@class='class1 
 class2']")).sendKeys(Keys.ENTER);

 // This below code failing intermittently
           **// Thread.sleep(2700);
           commonFunctionsObj.WaitUntilVisibilityOfElement(eleFilter);
           commonFunctionsObj.WaitUntilElementIsClickable(eleFilter);**

上面的地方间歇性失败。对此可能有什么等待策略。

© www.soinside.com 2019 - 2024. All rights reserved.