create account

[JAVA #15] [Web Automation #15] Selenium With TestNG #4 @DataProvider annotation [CN] by june0620

View this thread on: hive.blogpeakd.comecency.com
· @june0620 · (edited)
$8.72
[JAVA #15] [Web Automation #15] Selenium With TestNG #4 @DataProvider annotation [CN]
![redsjavahouse1591357_1280.jpg](https://steemitimages.com/0x0/https://files.steempeak.com/file/steempeak/june0620/DKldjbG3-reds-java-house-1591357_1280.jpg)
image source: [pixabay](https://pixabay.com/)

---

续上期继续探索TestNG的 annotation。
在自动化测试最重要的一个就是数据测试,叫‘数据驱动’测试。
假如在百度搜索搜索关键词,搜索国家名应显示相关国家信息,输入汇率应显示汇率转换器等。

幸好业界很多自动化测试工具都支持‘数据驱动’测试。
TestNG也不例外,可以用`DataProvider` 这个 annotation 来简单实现。不知道该功能的时候,我是用自己写的循环句来实现‘数据驱动’。但现在好了,有更好的方法可以实现了。

装载`@DataProvider` annotation函数必须返回`Object[][]` 或者 `Iterator<Object>`。
属性 `name` 与 `@Test` annotation的 `dataProvider` 属性相连。

下列例子是我用 `@DataProvider`来反复查询。<sub>(不经当事人同意乱使用了steemian的名字,请见谅,如需要删除请回帖,谢谢 ^^)</sub>

```
    @DataProvider(name = "steemians")
    public Object[][] members() {
     return new Object[][] {
     {"annepink"},
     {"gghite"},
     {"lucky2015"},
     {"honoru"},
     };
    }
```

`@Test` annotation的 `dataProvider` 属性与 `@DataProvider`的 `name` 属性值必须一致才可以正常获取steemian名。最后把数据传到函数内即可搜索。

```
    @Test(description = "搜索steemian。", dataProvider = "steemians")
    public void CASE_04_Search(String name) {
        driver.get(baseUrl + "/@" + name);
        /*
         * Some actions
         */
    }
```

运行后的报告也很完美。
![image.png](https://steemitimages.com/0x0/https://files.steempeak.com/file/steempeak/june0620/jFK2w1Vi-image.png)

**Sources:**

```
package com.steem.webatuo;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;

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.DataProvider;
import org.testng.annotations.Test;

import io.github.bonigarcia.wdm.WebDriverManager;

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

    @Test(enabled = false, description = "获取文章列表。")
    public void CASE_01_GetPosts() {
        List<WebElement> list = driver.findElements(By.xpath("//div[@id='posts_list']/ul/li"));
        assertTrue(!list.isEmpty(), "确认是否显示列表。");
        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(timeOut = 60000, description = "登录。")
    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"));
        assertNotNull(pw, "确认是否显示密码元素。");
        pw.sendKeys(Password.getPw());
        pw.submit();
        Thread.sleep(5000);
    }

    @Test(description = "撰写文章。")
    public void CASE_03_Write() throws InterruptedException {
        // Click the write Button
        List<WebElement> writeBtns = driver.findElements(By.xpath("//a[@href='/submit.html']"));
        assertEquals(writeBtns.size(), 1, "确认是否显示撰写按钮。");
        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);
    }
    @Test(description = "搜索steemians。", dataProvider = "steemians")
    public void CASE_04_Search(String name) {
        driver.get(baseUrl + "/@" + name);
        /*
         * Some actions
         */
    }
    @DataProvider(name = "steemians")
    public Object[][] members() {
     return new Object[][] {
     {"annepink"},
     {"gghite"},
     {"lucky2015"},
     {"honoru"},
     };
    }
    @AfterClass
    public void tearDownClass() {
        driver.quit();
    }
}
```

**演示视频:**
[https://youtu.be/UQSlN4KlgRs](https://youtu.be/UQSlN4KlgRs)
.
.
.
.
[Cookie 😅]
Seleniun java lib version: 3.141.59
java version: 13.0.1
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 46 others
properties (23)
authorjune0620
permlinkjava-15-web-automation-15-selenium-with-testng-4-dataprovider-annotation-cn
categoryhive-101145
json_metadata{"tags":["hive-101145","cn","cn-stem","steemstem","mini","zzan","sct-cn","sct-freeboard","dblog","java","sct","partiko"],"image":["https://files.steempeak.com/file/steempeak/june0620/DKldjbG3-reds-java-house-1591357_1280.jpg","https://files.steempeak.com/file/steempeak/june0620/jFK2w1Vi-image.png"],"links":["https://pixabay.com/","https://youtu.be/UQSlN4KlgRs"],"app":"partiko","format":"markdown","canonical_url":"https://www.steemcoinpan.com/@june0620/java-15-web-automation-15-selenium-with-testng-4-dataprovider-annotation-cn","users":["DataProvider","Test","BeforeClass","june0620","id","class","href","name","AfterClass"]}
created2020-03-17 12:50:45
last_update2020-03-17 12:58:39
depth0
children7
last_payout2020-03-24 12:50:45
cashout_time1969-12-31 23:59:59
total_payout_value4.734 HBD
curator_payout_value3.984 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length4,878
author_reputation118,592,211,436,406
root_title"[JAVA #15] [Web Automation #15] Selenium With TestNG #4 @DataProvider annotation [CN]"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id96,434,444
net_rshares31,835,422,579,695
author_curate_reward""
vote details (110)
@annepink ·
cn 标签不写 差评🙅 
个人建议哈...标题加个中文比较好 
!shop
@tipu curate

Posted using [Partiko Android](https://partiko.app/referral/annepink)
properties (22)
authorannepink
permlinkannepink-re-june0620-java-15-web-automation-15-selenium-with-testng-4-dataprovider-annotation-cn-20200317t125448308z
categoryhive-101145
json_metadata{"app":"partiko","client":"android"}
created2020-03-17 12:54:48
last_update2020-03-17 12:54:48
depth1
children5
last_payout2020-03-24 12:54:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length121
author_reputation1,032,301,266,727,142
root_title"[JAVA #15] [Web Automation #15] Selenium With TestNG #4 @DataProvider annotation [CN]"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id96,434,570
net_rshares0
@june0620 ·
我怎么又没加cn了呢,哎 哈哈🤗
多谢萍萍提醒和点赞 👍
properties (22)
authorjune0620
permlinkre-annepink-2020317t22337477z
categoryhive-101145
json_metadata{"tags":["esteem"],"app":"esteem/2.2.4-mobile","format":"markdown+html","community":"hive-125125"}
created2020-03-17 13:03:39
last_update2020-03-17 13:03:39
depth2
children2
last_payout2020-03-24 13:03:39
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length28
author_reputation118,592,211,436,406
root_title"[JAVA #15] [Web Automation #15] Selenium With TestNG #4 @DataProvider annotation [CN]"
beneficiaries
0.
accountesteemapp
weight300
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id96,434,784
net_rshares0
@annepink · (edited)
多谢june 没嫌弃我多事啊😬😂
properties (22)
authorannepink
permlinkannepink-re-june0620-re-annepink-2020317t22337477z-20200317t131220774z
categoryhive-101145
json_metadata{"app":"partiko","client":"android"}
created2020-03-17 13:12:21
last_update2020-03-17 13:12:42
depth3
children1
last_payout2020-03-24 13:12:21
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length16
author_reputation1,032,301,266,727,142
root_title"[JAVA #15] [Web Automation #15] Selenium With TestNG #4 @DataProvider annotation [CN]"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id96,434,973
net_rshares0
@june0620 ·
下贴开始标题也写上中文 😀
properties (22)
authorjune0620
permlinkre-annepink-2020317t22518939z
categoryhive-101145
json_metadata{"tags":["esteem"],"app":"esteem/2.2.4-mobile","format":"markdown+html","community":"hive-125125"}
created2020-03-17 13:05:21
last_update2020-03-17 13:05:21
depth2
children0
last_payout2020-03-24 13:05:21
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length13
author_reputation118,592,211,436,406
root_title"[JAVA #15] [Web Automation #15] Selenium With TestNG #4 @DataProvider annotation [CN]"
beneficiaries
0.
accountesteemapp
weight300
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id96,434,819
net_rshares0
@tipu ·
<a href="https://tipu.online/curator?annepink" target="_blank">Upvoted  &#128076;</a> (Mana: 5/20 - <a href="https://steempeak.com/steem/@tipu/tipu-curate-project-update-recharging-curation-mana" target="_blank">need recharge</a>?)
properties (22)
authortipu
permlinkre-annepink-re-june0620-java-15-web-automation-15-selenium-with-testng-4-dataprovider-annotation-cn-20200317t125448308z-20200317t125508
categoryhive-101145
json_metadata""
created2020-03-17 12:55:06
last_update2020-03-17 12:55:06
depth2
children0
last_payout2020-03-24 12:55:06
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length231
author_reputation55,922,745,798,079
root_title"[JAVA #15] [Web Automation #15] Selenium With TestNG #4 @DataProvider annotation [CN]"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id96,434,582
net_rshares0
@florianopolis ·
He said, ***'Stop doing wrong things and turn back to God! The kingdom of heaven is almost here.***'(Matthew 3:2) 
##  *Bro. Eli Challenges Atheism Belief, There is No God*
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.)***
https://youtu.be/QqkuNRO4Bt4
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](https://discord.gg/vzHFNd6) 
Join our Official Community: https://steemit.com/created/hive-182074
👍  
properties (23)
authorflorianopolis
permlink67imwthubzg
categoryhive-101145
json_metadata""
created2020-03-17 12:59:00
last_update2020-03-17 12:59:00
depth1
children0
last_payout2020-03-24 12:59:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length682
author_reputation-5,988,767,749,052
root_title"[JAVA #15] [Web Automation #15] Selenium With TestNG #4 @DataProvider annotation [CN]"
beneficiaries[]
max_accepted_payout10,000.000 HBD
percent_hbd100
post_id96,434,682
net_rshares1,232,840,010
author_curate_reward""
vote details (1)