[英]Exploitation of data provider elements inside test as array, using testNG
我創建了一個 selenium testNG webdriver 自動化程序,它可以抓取 excel 表中的數據並使用它們來填充一些字段並執行一些任務,
所以我寫了一個在任務被硬編碼時成功執行的代碼,但我想避免硬編碼和@test
內部的大量重復,所以我注入了一個數組列表,我想在其中利用 @DataProvider 元素,
這是代碼
package com.mycompany.app;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.excelreader.utility.getDataUtil;
public class testTab2 {
static WebDriver driver;
@BeforeTest
public void beforeTest()
{
System.setProperty("webdriver.chrome.driver", "C:\\Browsers drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://kdp.amazon.com/en_US/title-setup/paperback/new/details?ref_=kdp_BS_D_cr_ti");
driver.findElement(By.xpath("//*[@id='ap_email']")).sendKeys("email");
driver.findElement(By.xpath("//*[@id=\'ap_password\']")).sendKeys("password");
driver.findElement(By.xpath("//*[@id=\"signInSubmit\"]")).click();
}
@BeforeMethod
public void newTab()
{
driver.switchTo().newWindow(WindowType.TAB);
driver.get("https://kdp.amazon.com/en_US/title-setup/paperback/new/details?ref_=kdp_BS_D_cr_ti");
}
@Test(dataProvider = "getTestData")
protected static void testAmazon1(String innerPath, String coverPath, String book_Title, String subtitle,
String f_Name, String l_Name, String Description, String keyword1, String keyword2,
String keyword3, String keyword4, String keyword5, String keyword6, String keyword7,
String category_1, String category_2, String step_1, String step_2, String step_3,
String step_4, String step_5, String step_6, String step_7, String step_a, String step_b,
String step_c, String step_d, String step_e, String step_f, String step_g, String step_1final,String step_2final) throws Exception
{
//driver = new ChromeDriver();
Thread.sleep(4000);
driver.findElement(By.xpath("//button[@id='data-print-book-categories-button-proto-announce']")).click();
Thread.sleep(2000);
String[] category_A = new String [7];
category_A [0] = step_1;
category_A [1] = step_2;
category_A [2] = step_3;
category_A [3] = step_4;
category_A [4] = step_5;
category_A [5] = step_6;
category_A [6] = step_7;
int i = 0;
int index=0;
while (i<=6) {
if (category_A [i] != "kk") {
i++;
} else {
index=i;
System.out.println(index);
break;
}
}
for (int j=0; j<=index-2 ; j++) {
String expand = driver.findElement(By.xpath("//div[@id='icon-" + category_A [j] + "']")).getAttribute("class");
System.out.println("expand befor execution is: "+ expand);
String icon_plus = "icon expand-icon";
if(expand.equals(icon_plus)) {
driver.findElement(By.xpath("//div[@id='icon-" + category_A [j] + "']")).click();}
else {
System.out.println(category_A [j] + " is expanded");
}
}
driver.findElement(By.xpath("//input[contains(@id,'"+ step_1final +"')]")).click();
System.out.println("the following checkbox :" + step_1final + "is checked");
}
@DataProvider(parallel = false)
public Iterator<Object[]> getTestData() {
ArrayList<Object[]> testData = getDataUtil.getDataFromExcel();
return testData.iterator();
}
}
但是程序繼續運行,直到它到達數組,它給了我這個消息:
輸出
Starting ChromeDriver 79.0.3945.36 (XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-refs/branch-heads/XXXX@{#XXX}) on port XXXXX
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
janv. 27, 2020 5:30:51 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
如果有人有解決方案,我需要解決這個問題。 非常感謝您。
您還沒有包含您看到的錯誤消息的詳細信息,但是查看您的代碼,我猜您可能收到了如下所示的錯誤消息:
org.testng.internal.reflect.MethodMatcherException:
[public void com.rationaleemotions.stackoverflow.qn59935793.DataProviderSample.testMethod(java.lang.String,java.lang.String)] has no parameters defined but was found to be using a data provider (either explicitly specified or inherited from class level annotation).
Data provider mismatch
Method: testMethod([Parameter{index=0, type=java.lang.String, declaredAnnotations=[]}, Parameter{index=1, type=java.lang.String, declaredAnnotations=[]}])
Arguments: [(java.util.Collections$SingletonList) [a]]
你的測試代碼有問題。
您的測試方法具有以下簽名:
@Test(dataProvider = "getTestData")
protected static void testAmazon1(String innerPath, String coverPath, String book_Title, String subtitle,
String f_Name, String l_Name, String Description, String keyword1, String keyword2,
String keyword3, String keyword4, String keyword5, String keyword6, String keyword7,
String category_1, String category_2, String step_1, String step_2, String step_3,
String step_4, String step_5, String step_6, String step_7, String step_a, String step_b,
String step_c, String step_d, String step_e, String step_f, String step_g, String step_1final,String step_2final) throws Exception
{
但是您的數據提供者正在返回一個Iterator<Object[]>
。
基於您的數據提供程序中的以下代碼行
ArrayList<Object[]> testData = getDataUtil.getDataFromExcel();
無法弄清楚getDataFromExcel()
方法的確切返回類型是什么。
但是按照您在測試方法中的解釋,我猜您的getDataFromExcel()
可能正在返回一個列表,而您正試圖將其映射到測試方法中的各個元素。
那行不通。
下面的示例展示了如何直接使用List
。
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class DataProviderSample {
@DataProvider(name = "dp")
public Iterator<Object[]> getData() {
return Arrays.asList(
new Object[] {Collections.singletonList("a")}, new Object[] {Arrays.asList("x", "y")})
.iterator();
}
@Test(dataProvider = "dp")
public void testMethod(List<String> data) {
data.forEach(System.out::println);
}
}
更新 - 輸出
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//input[contains(@id,'self--help_self--management_general')]"}
(Session info: chrome=79.0.3945.130)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '4.0.0-alpha-3', revision: '8c567de6dc'
System info: host: 'UNKNOUN-PC', ip: '192.168.1.102', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '13.0.1'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 79.0.3945.130, chrome: {chromedriverVersion: 79.0.3945.36 (3582db32b3389..., userDataDir: C:\Users\moad\AppData\Local...}, goog:chromeOptions: {debuggerAddress: localhost:52780}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: 22669af4ff7fb4956b5951fd1aa2f1c6
*** Element info: {Using=xpath, value=//input[contains(@id,'self--help_self--management_general')]}
我添加了一個System.out.println(category_A [i] + " index = " + i);
在if 行之后,我發現該數組實際上正在接收數據,但問題出在if else 條件中。 我發現即使不滿足if條件,它也會繼續執行直到最后一個元素。
這是我得到的輸出。
nonfiction index = 0
self--help index = 1
self--help_self--management index = 2
kk index = 3
kk index = 4
kk index = 5
kk index = 6
我不知道這是什么原因?。
我只是替換那個if 語句
if (category_A [i] != "kk") {
與這
String breaker = "kk"
if ( !category_A [i].contentEquals(breaker)) {
它有效,我仍然不知道為什么但它有效,感謝您的幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.