简体   繁体   English

使用 testNG 将测试中的数据提供者元素用作数组

[英]Exploitation of data provider elements inside test as array, using testNG

I created a selenium testNG webdriver automation programe which grab data fome excel sheet and use them for fill some fields and execute some tasks,我创建了一个 selenium testNG webdriver 自动化程序,它可以抓取 excel 表中的数据并使用它们来填充一些字段并执行一些任务,

So I wrote a code that is successfully executed when the tasks are hard coded,but I want to avoid hard coding and lot of repetition inside @test , so I injected an array list in which I want to exploite @DataProvider elements,所以我写了一个在任务被硬编码时成功执行的代码,但我想避免硬编码和@test内部的大量重复,所以我注入了一个数组列表,我想在其中利用 @DataProvider 元素,

this is the code这是代码

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();

      }

}

But the program continues to run until it reaches the array and it gives me this message:但是程序继续运行,直到它到达数组,它给了我这个消息:

Output输出

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

If any one has a solution, I need to solve this problem.如果有人有解决方案,我需要解决这个问题。 thank you very much.非常感谢您。

You haven't included details of what error message you saw, but looking at your code, am guessing that you perhaps received an error message that looks like below:您还没有包含您看到的错误消息的详细信息,但是查看您的代码,我猜您可能收到了如下所示的错误消息:

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]]

There's a problem with your test code.你的测试代码有问题。

Your test method has the below signature:您的测试方法具有以下签名:

@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 
    {

But your data provider is returning back an Iterator<Object[]> .但是您的数据提供者正在返回一个Iterator<Object[]>

Based on the below line of code in your data provider基于您的数据提供程序中的以下代码行

ArrayList<Object[]> testData = getDataUtil.getDataFromExcel();

Its not possible to figure out what is the exact return type of your getDataFromExcel() method.无法弄清楚getDataFromExcel()方法的确切返回类型是什么。

But going by what you explained in your test method, I guess your getDataFromExcel() is perhaps returning back a list, and you are trying to map it to individual elements in your test method.但是按照您在测试方法中的解释,我猜您的getDataFromExcel()可能正在返回一个列表,而您正试图将其映射到测试方法中的各个元素。

That wont work.那行不通。

Below is a sample that shows how to work with List directly.下面的示例展示了如何直接使用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);
  }
}

UPDATE - output更新 - 输出

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')]}

I added a System.out.println(category_A [i] + " index = " + i);我添加了一个System.out.println(category_A [i] + " index = " + i); after the if line , and what I found is that the array is actually reciving data, but the problem is in if else condition .if 行之后,我发现该数组实际上正在接收数据,但问题出在if else 条件中 I found that even the if condition is not satisfied, it continues executing it untile the last element.我发现即使不满足if条件,它也会继续执行直到最后一个元素。

and this is the output I got.这是我得到的输出。

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

I don't know the raison of this?.我不知道这是什么原因?。

I just replace that if statement我只是替换那个if 语句

 if (category_A [i] != "kk") {

whith this与这

 String breaker = "kk"
 if ( !category_A [i].contentEquals(breaker)) {

and it works, I still dont know why but its working, and thanks for your help.它有效,我仍然不知道为什么但它有效,感谢您的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用testng并行运行数据提供者测试 - Run data provider tests in parallel using testng 使用 TestNg 中的数据提供程序运行依赖于不同参数的并行测试方法 - Run parallel test methods which are dependent with different parameter using Data Provider in TestNg TestNG - Selenium Java &gt; 数据提供者迭代并返回到之前的@Test - TestNG - Selenium Java > Data Provider Iteration and Return to previous @Test TestNG数据提供者 - TestNG Data provider 使用不同的数据提供程序在TestNG中重复整个测试类 - Repeat entire test class in TestNG, with different data provider 无法通过来自数据提供商的 TestNg 运行并行测试 - Unable to run parallel test via TestNg from DATA provider 在Testng中使用数据提供程序和并行方法,如何在给定测试的同一线程中在方法之前,方法之后和测试中运行? - Using data-provider and parallel in Testng, how to run before method, after method and test in same thread for a given test.? 使用提供程序时覆盖TestNG测试名称并忽略参数 - Override TestNG Test name when using a provider and omit parameters 从JSON数组读取数据以供testng中的数据提供者使用 - Reading data from JSON Array for data provider in testng 将列表转换为二维数组 Java 以用于 TestNG 数据提供程序 - Converting List to Two dimensional array Java for TestNG data provider
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM