发生异常时,@ After注释是否始终在Selenium中执行?

时间:2017-08-04 10:45:05

标签: selenium

在发生例外的情况下;在编写Selenium测试用例时是否有必要在catch块中关闭驱动程序? 我在tearDown()方法中关闭了驱动程序,该方法具有@After注释。

3 个答案:

答案 0 :(得分:3)

不,如果您已在@After注释中完成此操作,则不需要在catch块中关闭/退出驱动程序。

下面。

  

即使是Before或Test,所有@After方法都可以保证运行   抛出异常。

取自以下网站 http://junit.sourceforge.net/javadoc/org/junit/After.html

因为没有发生异常,所以这个注释将被执行。

以下示例使用 TestNG ,但我认为 JUnit @After注释与 TestNG @AfterMethod相同

在下面的示例中,即使test将抛出java.lang.ArithmeticException: / by zero,也会执行tearDown方法并关闭所有浏览器。

public class GoogleTest {

    WebDriver driver;

    @BeforeMethod
    public void setup() {
        driver = new FirefoxDriver();
    }

    @AfterMethod
    public void tearDown() {
        driver.quit();
        System.out.println("Closed all the browsers");
    }

    @Test
    public void visitGoogle(){
        driver.get("https://google.com");
        int a=1/0;
    }

}

在Junit报告中,您将看到两件事。

错误:如果发生任何异常,则会将其报告为错误

失败:如果任何断言失败,则会报告为失败

在你想要继续流程之前,我不会处理异常。像webdriver的ElementNotFoundElementNotVisible这样的例外处理更好。它将无法通过测试,您可以看到整个堆栈跟踪,这将帮助您调试根本原因。

答案 1 :(得分:0)

@After与selenium无关。如果您使用的是Java,它是JUNIT的注释。在tearDown()中关闭驱动程序或指定@After函数没有这样的规则。虽然在测试用例完成后退出驱动程序实例是一种很好的做法。如果另一个脚本将触发,quit将关闭所有浏览器实例并清除机器中的内存和资源。 而且,处理错误也是一种很好的做法。您应该处理在运行时脚本执行期间可能发生的错误。示例: - I / O操作,文件上载等

示例: -

  WebDriver driver=null;
 @BeforeMethod
    public void setup() {
        System.setProperty("webdriver.chrome.driver","D:\\Workspace\\JmeterWebdriverProject\\src\\lib\\chromedriver.exe");
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--start-maximized");
        driver = new ChromeDriver(chromeOptions);
    }

@AfterMethod
public void tearDown() {
    //driver.quit();
    System.out.println("Closed all the browsers");
}

@Test
public void visitGoogle(){
    driver.get("https://google.com");
    try {
    int a=1/0;
    }
    catch(Exception ex){
        ex.printStackTrace();
        driver.quit();
    }
}

希望它能帮到你

答案 2 :(得分:0)

Small update: there is an option in testNG for annonations i.e. beforetest, aftertest. And that option is @AfterTest(alwaysRun = true)...once this is set then the @AfterTest will always execute even if there was exception in the methods before.

相关问题