Selenium 与 JUnit / TestNG 指南
上次更新:2024 年 1 月 8 日
1. 简介
本文是对使用 Selenium 并使用 JUnit 和 TestNG 编写测试的快速、实用的介绍。
2. Selenium 集成
在本节中,我们将从一个简单的场景开始——打开浏览器窗口,导航到给定的 URL,并查找页面上所需的内容。
2.1. Maven 依赖
在 pom.xml 文件中,添加以下依赖
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.4.0</version>
</dependency>
可以在 Maven Central Repository 中找到最新版本。
2.2. Selenium 配置
首先,创建一个名为 SeleniumConfig 的新的 Java 类文件
public class SeleniumConfig {
private WebDriver driver;
//...
}
鉴于我们使用的是 Selenium 3.x 版本,我们需要使用名为 webdriver.gecko.driver 的系统属性指定 GeckoDriver 文件的路径(基于您的操作系统)。最新版本的 GeckoDriver 可以从 Github Geckodriver Releases 下载。
现在,让我们在构造函数中初始化 WebDriver;我们还将设置 5 秒作为 WebDriver 等待页面上元素出现的时间限制
public SeleniumConfig() {
Capabilities capabilities = DesiredCapabilities.firefox();
driver = new FirefoxDriver(capabilities);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
static {
System.setProperty("webdriver.gecko.driver", findFile("geckodriver.mac"));
}
static private String findFile(String filename) {
String paths[] = {"", "bin/", "target/classes"};
for (String path : paths) {
if (new File(path + filename).exists())
return path + filename;
}
return "";
}
这个配置类包含一些我们现在将忽略的方法,但我们将在本系列的第二部分中更多地了解这些方法。
接下来,我们需要实现一个 SeleniumExample 类
public class SeleniumExample {
private SeleniumConfig config;
private String url = "https://baeldung.cn/";
public SeleniumExample() {
config = new SeleniumConfig();
config.getDriver().get(url);
}
// ...
}
在这里,我们将初始化 SeleniumConfig 并设置要导航到的所需 URL。 类似地,我们将实现一个简单的 API 来关闭浏览器并获取页面的标题
public void closeWindow() {
this.config.getDriver().close();
}
public String getTitle() {
return this.config.getDriver().getTitle();
}
为了导航到 baeldung.com 的 About 部分,我们需要创建一个 closeOverlay() 方法,该方法检查并关闭主页加载时的叠加层。 之后,我们使用 getAboutBaeldungPage() 方法导航到关于 Baeldung 的页面
public void getAboutBaeldungPage() {
closeOverlay();
clickAboutLink();
clickAboutUsLink();
}
private void closeOverlay() {
List<WebElement> webElementList = this.config.getDriver()
.findElements(By.tagName("a"));
if (webElementList != null) {
webElementList.stream()
.filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title")))
.filter(WebElement::isDisplayed)
.findAny()
.ifPresent(WebElement::click);
}
}
private void clickAboutLink() {
Actions actions = new Actions(config.getDriver());
WebElement aboutElement = this.config.getDriver()
.findElement(By.id("menu-item-6138"));
actions.moveToElement(aboutElement).perform();
}
private void clickAboutUsLink() {
WebElement element = this.config.getDriver()
.findElement(By.partialLinkText("About Baeldung."));
element.click();
}
我们可以检查显示的页面上是否有所需的信息
public boolean isAuthorInformationAvailable() {
return this.config.getDriver()
.getPageSource()
.contains("Hey ! I'm Eugen");
}
接下来,我们将使用 JUnit 和 TestNG 测试这个类。
3. 使用 JUnit
让我们创建一个名为 SeleniumWithJUnitLiveTest: 的新测试类
public class SeleniumWithJUnitLiveTest {
private static SeleniumExample seleniumExample;
private String expectedTitle = "About Baeldung | Baeldung";
// more code goes here...
}
我们将使用来自 org.junit.BeforeClass 的 @BeforeClass 注解来执行初始设置。 在这个 setUp() 方法中,我们将初始化 SeleniumExample 对象
@BeforeClass
public static void setUp() {
seleniumExample = new SeleniumExample();
}
以类似的方式,当我们的测试用例完成时,我们应该关闭新打开的浏览器。 我们将使用 @AfterClass 注解来执行此操作——在测试用例执行完成后清理设置
@AfterClass
public static void tearDown() {
seleniumExample.closeWindow();
}
请注意我们的 SeleniumExample 成员变量上的 static 修饰符——因为我们需要在 setUp() 和 tearDown() 静态方法中使用这个变量——@BeforeClass 和 @AfterClass 只能在静态方法上调用。
最后,我们可以创建完整的测试
@Test
public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() {
seleniumExample.getAboutBaeldungPage();
String actualTitle = seleniumExample.getTitle();
assertNotNull(actualTitle);
assertEquals(expectedTitle, actualTitle);
assertTrue(seleniumExample.isAuthorInformationAvailable());
}
这个测试方法断言网页的标题不为 null 并且设置如预期。除此之外,我们检查页面是否包含预期的信息。
当测试运行时,它只是在 Firefox 中打开 URL,然后在验证了网页的标题和内容之后关闭它。
4. 使用 TestNG
现在让我们使用 TestNG 运行我们的测试用例/套件。
请注意,如果您使用的是 Eclipse,TestNG 插件可以从 Eclipse Marketplace 下载和安装。
首先,让我们创建一个新的测试类
public class SeleniumWithTestNGLiveTest {
private SeleniumExample seleniumExample;
private String expectedTitle = "About Baeldung | Baeldung";
// more code goes here...
}
我们将使用来自 org.testng.annotations.BeforeSuite 的 @BeforeSuite 注解来实例化我们的 SeleniumExample 类。 setUp() 方法将在激活测试套件之前启动
@BeforeSuite
public void setUp() {
seleniumExample = new SeleniumExample();
}
类似地,我们将使用来自 org.testng.annotations.AfterSuite 的 @AfterSuite 注解来完成测试套件后关闭我们打开的浏览器
@AfterSuite
public void tearDown() {
seleniumExample.closeWindow();
}
最后,让我们实现我们的测试
@Test
public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() {
seleniumExample.getAboutBaeldungPage();
String actualTitle = seleniumExample.getTitle();
assertNotNull(actualTitle);
assertEquals(expectedTitle, actualTitle);
assertTrue(seleniumExample.isAuthorInformationAvailable());
}
在成功完成测试套件后,我们可以在项目的test-output文件夹中找到HTML和XML报告。这些报告总结了测试结果。
5. 结论
在这篇快速文章中,我们重点介绍了使用JUnit和TestNG编写Selenium 3测试的快速入门。
支持本文的代码可在 GitHub 上获取。 一旦你以 Baeldung Pro 会员 身份登录,就开始学习并在项目上进行编码。















