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



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

不,如果您在注释中这样做@After则无需关闭/退出 catch 块中的驱动程序。

这里。

保证所有@After方法都运行,即使 之前 或 测试 方法引发异常。

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

因为是否发生了异常并不重要,因此将执行此注释。

以下示例正在使用TestNG,但我认为@AfterJUnit的注释与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报告中,您将看到两件事。

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

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

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

@After与硒无关。如果你使用的是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();
}
}

希望对您有所帮助

小更新:testNG 中有一个用于枚举的选项,即测试前、测试后。该选项是@AfterTest(alwaysRun = true(...设置后,即使之前的方法中存在异常,@AfterTest也将始终执行。

最新更新