【问题标题】:Catching exceptions and errors from junit tests without stopping the program?在不停止程序的情况下从 junit 测试中捕获异常和错误?
【发布时间】:2014-07-29 16:58:14
【问题描述】:

我正在使用 junit 和 selenium 来测试 Web 应用程序,并且我有一个正在运行的测试套件。有时,当网页无法在浏览器中正确加载时,测试会失败,这并不是实际应用程序的错误。为了解决这个问题,我想捕获任何第一次出现的错误并再次运行测试以确保问题确实出在应用程序上。 我试过下面的代码。

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);
    }

我也试过了

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");
            }
        }

但是在这两个测试中,程序第一次遇到错误时会完全停止测试。尽管失败了,但我需要能够多次运行这些测试。

【问题讨论】:

标签: java testing selenium junit


【解决方案1】:

我相信处理此问题的最简单方法是在开始执行测试之前检查您的页面是否已加载。我不确定您的测试导航是如何工作的。但对我来说,我们使用的是这样的东西

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

在 SomePage() 对象内部使用一个唯一的选择器,在构造函数内部等待它存在并将其包装在 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")));
}

我的是 C#。希望这会有所帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-25
    • 2011-05-01
    • 2020-05-13
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 2011-04-11
    相关资源
    最近更新 更多