[JAVA #12] [Web Automation #12] Selenium With TestNG #1 Installing TestNG [CN]

avatar
(Edited)

redsjavahouse1591357_1280.jpg
image source: pixabay


今天开始分几步学一下TestNG与Selenium的结合。
TestNG 顾名思义是一个测试专用框架。可支持很多annotation来管理测试用例并且提供很完美(?)的测试报告。
TestNG是基于开发者常用的Junit开发的,所以有很多类似的地方,但这个框架更适合QA使用。

到现在,我都是在main()函数里写一堆代码,这样会导致代码一多很难维护的地步。
比如有一下用例。

a. 打开浏览器 
b. 获取他人文章
c. 登录
d. 写文
e. 关闭浏览器
  • 很难维护修改代码。
    倘若d用例需要修改,为节省时间最好把b和c注释掉,来回注释会难免失误,你懂的。
  • 公用代码难管理
    a与e是主用例运行前必须运行的代码。但强制写在main函数也很不方便。
  • 用例难维护
    如果用例上百甚至上千就很难维护main代码。

即极其需要TestNG等框架。


那,首先安装下TestNG。

  1. Eclipse help菜单 > Install New Software... > 在弹窗 Work with 输入 http://dl.bintray.com/testng-team/testng-eclipse-release/ 会自动搜索TestNG。跟指南走就是了。
    image.png

  2. 安装过程中会时不时出现这样的弹窗,点击 Install anyway 并点击Restart Now即可完成安装。
    image.png

  3. 点击右键左侧项目 > Properties > Java Build Path > Libraries > Add Library.. > 添加 TestNG 就可以使用了,左侧应该会显示TestNG 库。准备就绪。
    Install2.png

  4. 开始用TestNG的 annotation来修改我的脏代码。
    TestNG支持很多 annotation,先简单介绍下最常用的几个吧。
    @Test - 表示一个用例,例如登录,写文等等。
    @BeforeClass - @Test函数运行之前必须先运行此annotation,通常写入通用设置。
    @AfterClass - @Test函数运行后必须运行的annotation。一般用户结束进程。

上述的用例改为TestNG版本如下。

AS-IS:
package com.steem.webatuo;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class Steemit {

    public static void main(String[] args) throws InterruptedException {
        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();
        driver.get("steemit.com/@june0620/feed");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        
        List<WebElement> list = driver.findElements(By.xpath("//div[@id='posts_list']/ul/li"));
        for(WebElement post : list) {
            String title = post.findElement(By.xpath("descendant::h2/a")).getText();
            String author = post.findElement(By.xpath("descendant::span[@class='user__name']")).getText();
            System.out.println(author + "的文章: " + title);
        }
//Click the login button
 driver.findElement(By.linkText("login")).click();
 // type id
 driver.findElement(By.name("username")).sendKeys("june0620");
 // type pw and submit
 WebElement pw = driver.findElement(By.name("password"));
 pw.sendKeys(Password.getPw());
 pw.submit();
 Thread.sleep(5000);
 // Click the write Button 
 List<WebElement> writeBtns = driver.findElements(By.xpath("//a[@href='/submit.html']"));
 for(WebElement writeBtn : writeBtns) {
 if(writeBtn.isDisplayed()) {
 writeBtn.click();
 Thread.sleep(2000);
 //type Text and Keys
 WebElement editor = driver.findElement(By.xpath("//textarea[@name='body']"));
 String keys = Keys.chord(Keys.LEFT_SHIFT, Keys.ENTER);
 editor.sendKeys("hello!! world", keys, "hello!!! STEEMIT", Keys.ENTER, "안녕, 스팀잇", Keys.ENTER, "你好!似提姆");
 break;
 }
 }
 
 Thread.sleep(5000);
        driver.quit();
    }

}

TO-BE:
package com.steem.webatuo;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import io.github.bonigarcia.wdm.WebDriverManager;

public class Steemit {
    WebDriver driver;

    @BeforeClass
    public void SetUp() {
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
        driver.get("steemit.com/@june0620/feed");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
    }

    @Test
    public void CASE_01_GetPosts() {
        List<WebElement> list = driver.findElements(By.xpath("//div[@id='posts_list']/ul/li"));
        for (WebElement post : list) {
            String title = post.findElement(By.xpath("descendant::h2/a")).getText();
            String author = post.findElement(By.xpath("descendant::span[@class='user__name']")).getText();
            System.out.println(author + "的文章: " + title);

    }

    @Test
    public void CASE_02_Login() throws InterruptedException {
        // Click the login button
        driver.findElement(By.linkText("login")).click();
        // type id
        driver.findElement(By.name("username")).sendKeys("june0620");
        // type pw and submit
        WebElement pw = driver.findElement(By.name("password"));
        pw.sendKeys(Password.getPw());
        pw.submit();
        Thread.sleep(5000);
    }

    @Test
    public void CASE_03_Write() throws InterruptedException {
        // Click the write Button
        List<WebElement> writeBtns = driver.findElements(By.xpath("//a[@href='/submit.html']"));
                Assert.assertFalse(writeBtns.isEmpty());
        for (WebElement writeBtn : writeBtns) {
            if (writeBtn.isDisplayed()) {
                writeBtn.click();
                Thread.sleep(2000);
                // type Text and Keys
                WebElement editor = driver.findElement(By.xpath("//textarea[@name='body']"));
                String keys = Keys.chord(Keys.LEFT_SHIFT, Keys.ENTER);
                editor.sendKeys("hello!! world", keys, "hello!!! STEEMIT", Keys.ENTER, "안녕, 스팀잇", Keys.ENTER, "你好!似提姆");
                break;
            }
        }
        Thread.sleep(5000);
    }

    @AfterClass
    public void tearDownClass() {
        driver.quit();
    }
}

可以看出代码可读性高了不少。
如想修改CASE_03_Write()把其他的@Test注释即可。
在代码点击右键 > Run As.. > TestNG Test 可以运行代码并生成测试报告。👇
run1.png
失败的测试用例显示为红色以便维护。👇 下图是没有找到撰写按钮没有通过 TestNG的断言(Asserting)。
断言(Asserting)在下一节深度研究
image.png

错误代码:

List<WebElement> writeBtns = driver.findElements(By.xpath("//Invalid xPath"));
Assert.assertFalse(writeBtns.isEmpty());

.
.
.
.
[Cookie 😅]
Seleniun java lib version: 3.141.59
java version: 13.0.1

TestNG 介绍
https://en.wikipedia.org/wiki/TestNG
https://testng.org

TestNG 安装方法 - https://www.guru99.com/install-testng-in-eclipse.html)

TestNG annotation 参考 - https://www.tutorialspoint.com/testng/testng_basic_annotations.htm



0
0
0.000
3 comments
avatar

According to the Bible, Graven Images: Should You Worship These According to the Bible?

Watch the Video below to know the Answer...

(Sorry for sending this comment. We are not looking for our self profit, our intentions is to preach the words of God in any means possible.)


Comment what you understand of our Youtube Video to receive our full votes. We have 30,000 #SteemPower. It's our little way to Thank you, our beloved friend.
Check our Discord Chat
Join our Official Community: https://steemit.com/created/hive-182074

0
0
0.000
avatar

啪啪
建议加上cn-stem, cn-programming这几个标签,看看能不能得到SteemSTM的奖励。

0
0
0.000
avatar

cn-stem是加上了,还有cn-programming标签呢?
谢谢分享~ 😄

0
0
0.000