跨不同的类访问@BeforeTest 和@AfterClass (TestNG) 中的变量? [英] Access variable in @BeforeTest and @AfterClass (TestNG) across separate classes?
问题描述
我正在使用 Java 和 TestNG 框架为我的公司编写一些 selenium 自动化 UI 测试.我在 Base
类中定义驱动程序,我想在 @BeforeTest
中实际初始化驱动程序并在 @AfterTest
中退出它方法.假设它们在不同的类中,Java 的方法是什么?我知道如何让它在同一个班级中工作,但不知道如何在不同的班级中工作.这是我的 Base.java
文件:
I am writing some selenium automated UI tests for my company using Java and the TestNG framework. I am defining the driver in a Base
class, and I want to actually initialize the driver in an @BeforeTest
and quit it in a @AfterTest
method. What is the Java way to do that, assuming they are in different classes? I know how to make it work in the same class, but not over separate classes. Here is my Base.java
file:
public class Base {
public static WebDriver driver = null;
public WebDriver getDriver() {
driver = new ChromeDriver();
return driver;
}
}
现在,我想拥有一个单独的 Setup 类和一个单独的 Teardown 类.如果我要在同一个 @Test
中定义所有这些,我会这样做:
Now, I want to have a separate Setup class and a separate Teardown class. If I was going to define all of this in the same @Test
, I would do it this way:
@Test
public void testOne() {
Base b = new Base();
WebDriver driver = b.getDriver();
// Do test-y things here.
driver.quit();
}
我该如何设置?尝试学习正确的方法来做到这一点,而不是一起破解某些东西.如果需要,我还可以提供更多信息.谢谢!
How would I set this up? Trying to learn the right way to do this, and not hack something together. I can also provide more information if needed. Thanks!
推荐答案
使用继承.
public class TestBase {
protected WebDriver driver;
@BeforeClass
public void setUp(){
System.out.println("I am in setUp method.");
//WebDriver instantiation etc.
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized", "--disable-cache");
driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@AfterClass
public void tearDown(){
System.out.println("I am in tearDown method.");
//You can clean up after tests.
driver.close();
}
}
然后就可以使用继承了.注意extends
关键字:
And then inheritance can be used. Pay attention to the extends
keyword:
public class ParticularTest extends TestBase {
@Test
public void testMethod() {
System.out.println("I am in testMethod.");
//Your driver from TestBase is accessible here.
//Your assertions come here.
}
}
稍后您可以执行ParticularTest.java
.输出:
Later on you can just execute ParticularTest.java
.
Output:
I am in setUp method.
I am in testMethod.
I am in tearDown method.
这篇关于跨不同的类访问@BeforeTest 和@AfterClass (TestNG) 中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!