如何用不同的 csv 行循环这个测试?

我是硒测试的初学者。我写了这段代码,它可以工作,但我需要用另一个 csv 行循环这个测试。

我花了将近 10 个小时试图做到这一点。

我正在尝试做的场景:

  1. 网络浏览器正在打开 go to url

  2. 从第一行使用 CSV 文件中的数据登录

  3. 驱动程序正在重新启动并执行相同的操作,但使用 csv 文件中第二行的数据。

我还尝试使用 aftermethod/afterclass 重新启动测试,但它不起作用。

public class CSVdataread {

    private WebDriver driver;

    String baseUrl = "URL";

    String CSV_file = "C:\\Users\\xxxxxxxxxxx\\Desktop\\TestData.csv";


    @BeforeClass

    public void openBrowser() {

        System.setProperty("webdriver.chrome.driver", "C:\\Users\\xxxxxxxxxxxx\\Desktop\\webdriver\\chromedriver.exe");

        driver = new ChromeDriver();

        driver.navigate().to("URL");

        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    }


    @Test

    public void verify_Search() throws InterruptedException, IOException {

        CSVReader reader = new CSVReader(new FileReader(CSV_file));

        String[] cell;


        while((cell = reader.readNext()) != null) 

            for (int i = 0; i < 1; i++) {

                String name = cell[i];

                String email = cell[i + 1];

                String baseUrl = "http://xxxxx.xxx/xxxx/";

                driver.findElement(By.xpath("//input[@id='useridFormField-inputEl']")).sendKeys(name);

                driver.findElement(By.xpath("//input[@id='userpasswordFormField-inputEl']")).sendKeys(email);

                {

                    driver.quit();

                }

            }

        }

    } 


潇潇雨雨
浏览 137回答 3
3回答

忽然笑

JUnit 4 解决方案。这个会很大。。。首先,让我们从CSVReader一些好的实践和代码可读性开始。在您的测试中,您读取 CSV 数据并在测试中使用它们。读取数据不是测试的责任。测试应该已经提供给它的所有数据。它被称为DataProvider。这个术语实际上是在TestNG测试框架中使用的,就像@user861594 建议的那样。因此,您应该有一些东西可以为您的测试提供数据。但这已经是第 2 步了。由于您知道您将从 CSV 文件中逐行读取数据,因此您应该创建一个适当的类来从 CSV 中读取数据。这是一个例子:public class CSVReader {&nbsp; &nbsp; private static final String DEFAULT_SEPARATOR = ",";&nbsp; &nbsp; private BufferedReader reader;&nbsp; &nbsp; private List<String> lines;&nbsp; &nbsp; public CSVReader(File file) throws FileNotFoundException {&nbsp; &nbsp; &nbsp; &nbsp; this.reader = new BufferedReader(new FileReader(file));&nbsp; &nbsp; &nbsp; &nbsp; lines = this.reader.lines().collect(Collectors.toList());&nbsp; &nbsp; }&nbsp; &nbsp; public String[] getRow(int rowNumber) {&nbsp; &nbsp; &nbsp; &nbsp; return lines.get(rowNumber).split(DEFAULT_SEPARATOR);&nbsp; &nbsp; }&nbsp; &nbsp; public int getRowCount() {&nbsp; &nbsp; &nbsp; &nbsp; return lines.size();&nbsp; &nbsp; }}构造CSVReader函数接受 aFile作为参数并创建适当的对象以以特定方式读取数据(例如: read as String)。然后,读取 CSV 文件中的数据,就像在普通 TXT 文件中一样,将行保存在内存中以备后用。然后我们创建2个方法。首先是getRowCount它给了我们行/数据集的总数。其次是getRow从列表中收集特定行并将其保存到String[]数组中以备后用。String[]数组有一个类似 1 Excel 行的演示文稿:data index 0 | data index 1 | data index 2 | data index 3我们有一个类可以让我们轻松读取文件。让我们创建DataProvider为了向测试提供数据,我们需要使用@Parameters注解并返回Collection<Object[]>到我们的测试。我稍后会谈到这一点。所以,让我们在我们的DataProviderpublic class CSVDataProvider {&nbsp; &nbsp; public Collection<Object[]> getData() throws FileNotFoundException {&nbsp; &nbsp; &nbsp; &nbsp; CSVReader reader = new CSVReader(new File("C:\\Users\\xxxxxxxxxxx\\Desktop\\TestData.csv"));&nbsp; &nbsp; &nbsp; &nbsp; int rowCount = reader.getRowCount();&nbsp; &nbsp; &nbsp; &nbsp; Object[][] data = new Object[rowCount][2];&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < rowCount; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Object[] singleRow = reader.getRow(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data[i][0] = singleRow[0];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data[i][1] = singleRow[1];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return Arrays.asList(data);&nbsp; &nbsp; }}我假设您在 CSV 文件中只有登录名和密码。这就是我创建二维数组的原因new Object[rowCount][2]。rowCount我们通过提供它必须存储的元素数量来创建数组,并且我们知道变量中有多少行。2 表示我们每行只有 2 个数据。登录名和密码。如果你想使用额外的元素,例如 - 用户的角色,你可以修改为[3]在for循环中,我们将数据从 CSV 文件转换为数组并将其返回以供以后使用。现在,让我们谈谈我们的测试类。@RunWith(Parameterized.class)public class OurTest {&nbsp; &nbsp; private String login, password;&nbsp; &nbsp; public OurTest(String login, String password) {&nbsp; &nbsp; &nbsp; &nbsp; this.login = login;&nbsp; &nbsp; &nbsp; &nbsp; this.password = password;&nbsp; &nbsp; }&nbsp; &nbsp; @Parameterized.Parameters(name = "{index}: Login: ({0}) Password: ({1})")&nbsp; &nbsp; public static Collection<Object[]> data() throws FileNotFoundException {&nbsp; &nbsp; &nbsp; &nbsp; return new CSVDataProvider().getData();&nbsp; &nbsp; }&nbsp; &nbsp; @Test&nbsp; &nbsp; public void test() {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(String.format("login : %s | Password: %s", login, password));&nbsp; &nbsp; }}为了将参数传递DataProvider给我们的测试,我们需要 1. 用注释类@RunWith(Parameterized.class) 2. 创建一个返回 @Parameters 的方法Collection<Object[]> with annotation3. 创建一个构造函数来反映我们接受什么样的数据。关于第 3 点,这就是为什么我用String loginand创建了一个 2 参数构造函数String password。我们正在传递这两个参数。OurTestJUnit 将为每个测试创建一个新实例并传递不同的行。在test我刚刚打印的方法中,我们从DataProvider我没有提供一个完全有效的解决方案,因为我希望你尝试调整你的测试来学习这种特定的方法。它也被称为Data-driven Testing。我们只有一种测试方法,但 CSV 文件中的每一行都将作为单独的测试运行。希望能帮助到你!

白板的微信

看起来你想用一组测试数据迭代你的测试。在这种情况下,您应该使用 TestNG数据提供程序功能。public class CSVdataread {&nbsp; &nbsp; private WebDriver driver;&nbsp; &nbsp; String baseUrl = "URL";&nbsp; &nbsp; String CSV_file = "C:\\Users\\xxxxxxxxxxx\\Desktop\\TestData.csv";&nbsp; &nbsp; @BeforeMethod&nbsp; &nbsp; public void openBrowser() {&nbsp; &nbsp; &nbsp; &nbsp; System.setProperty("webdriver.chrome.driver", "C:\\Users\\xxxxxxxxxxxx\\Desktop\\webdriver\\chromedriver.exe");&nbsp; &nbsp; &nbsp; &nbsp; driver = new ChromeDriver();&nbsp; &nbsp; &nbsp; &nbsp; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);&nbsp; &nbsp; }&nbsp; &nbsp; @Test(dataProvider="users-data")&nbsp; &nbsp; public void verify_Search(String name, String email) throws InterruptedException, IOException {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;String baseUrl = "http://xxxxx.xxx/xxxx/";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;driver.navigate().to(baseUrl);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;driver.findElement(By.xpath("//input[@id='useridFormField-inputEl']")).sendKeys(name);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;driver.findElement(By.xpath("//input[@id='userpasswordFormField-inputEl']")).sendKeys(email);&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;//This method will provide data to any test method that declares that its Data Provider&nbsp; &nbsp; &nbsp;@DataProvider(name = "users-data")&nbsp; &nbsp; &nbsp;public Iterator<Object[]> createDataFromCSV() {&nbsp; &nbsp; &nbsp; &nbsp;CSVReader reader = new CSVReader(new FileReader(CSV_file));&nbsp; &nbsp; &nbsp; &nbsp;List<Object[]> data = new ArrayList<Object[]>();&nbsp; &nbsp; &nbsp; &nbsp;//read csv data to list&nbsp; &nbsp; &nbsp; &nbsp;return data.iterator();&nbsp; &nbsp; }&nbsp; &nbsp; @AfterMethod&nbsp; &nbsp; public void closeBrowser() {&nbsp; &nbsp; &nbsp; &nbsp; driver.quit();&nbsp; &nbsp; }&nbsp;}&nbsp;您还可以利用可用的 data-provider-extension。例如,使用 qaf 您无需为驱动程序管理或数据提供者编写代码。您的测试类将如下所示:public class CSVdataread&nbsp; extends WebDriverTestCase{&nbsp; &nbsp; @QAFDataProvider(dataFile="resources/user-data.csv")&nbsp; &nbsp; @Test()&nbsp; &nbsp; public void verify_Search(String name, String email) throws InterruptedException, IOException {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;String baseUrl = "http://xxxxx.xxx/xxxx/";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;getDriver().navigate().to(baseUrl);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;getDriver().findElement(By.xpath("//input[@id='useridFormField-inputEl']")).sendKeys(name);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//another way of finding element...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;getDriver().findElement("xpath=//input[@id='userpasswordFormField-inputEl']").sendKeys(email);&nbsp; &nbsp; &nbsp;}&nbsp;}&nbsp;

HUH函数

你的 while 循环看起来坏了。while 循环中的 for 循环似乎弄乱了您的登录过程。while((cell = reader.readNext())!=null) { // iterate through csv file&nbsp; String name = cell[0]; // cell is current row, you need first column for name&nbsp; String email = cell[1]; // second column for email (as password?)&nbsp; // what do you want to do with baseUrl here?&nbsp; driver.findElement(By.xpath("//input[@id='useridFormField-inputEl']")).sendKeys(name);&nbsp; driver.findElement(By.xpath("//input[@id='userpasswordFormField-inputEl']")).sendKeys(email);&nbsp; // you need to check the successful login here&nbsp; // then logout and open main page&nbsp; // do not quit before you are finished&nbsp;}// quit after the loop is finisheddriver.quit();如果不了解网站,就不可能告诉您如何检查成功登录和执行注销。我可以建议您花一些精力来学习不太复杂的任务吗?您似乎在使用基本 Java 元素时遇到了很多麻烦。从未停止学习。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java