简体   繁体   中英

Catching exceptions and errors from junit tests without stopping the program?

I am using junit and selenium to test a web application and I have a test suite that I'm running. Sometimes when a web page fails to load properly in the browser, tests will fail through no fault of the actual application. To remedy this I wanted to catch any first time errors and run tests again to ensure that the problem indeed lies with the application. I've tried the code below.

try{
        ts.runTest(ts.testAt(testNum), a);
    }
    catch (Error er){
        ts.runTest(ts.testAt(testNum),  a);
    }
    catch (Exception e){
        ts.runTest(ts.testAt(testNum),  a);
    }

Ive also tried this

ts.runTest(ts.testAt(testNum),  a);
if (!a.wasSuccessful()){
            ts.runTest(ts.testAt(testNum), a);
            if (!a.wasSuccessful()){
                fail();
                System.out.println("Test "+testNum+" failed");
            }
        }

But in both tests the program stops testing entirely the first time it encounters an error. I need to be able to run these tests multiple times despite failures.

I beleive the easiest way to handle this issue will be to check if your page has loaded before even start executing tests. I am not sure how your tests navigation works. But for me it's something like this we use

public SomePage ClickUpdate()
    {
        Driver.FindElement(By.Id("MyId")).Click();
        //taking page objects in return
        return new SomePage (Driver);
    }

And inside the SomePage() object use a unique selector and inside the constructor wait until that to exist and wrap that in try catch

try
{
    var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(5));
    wait.Until(ExpectedConditions.ElementExists(By.Id("Your Id")));
}
catch (YourException)
{
    Driver.Navigate().Refresh();
    // Or you can perform another click to allow the page to load
    var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(5));
    wait.Until(ExpectedConditions.ElementExists(By.Id("Your Id")));
}

Mine is C#. Hope this helps

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