如何在 Selenium 2 中编写带有参数的方法?

How to write a method with a parameter in Selenium 2?

正在测试此站点:http://store.demoqa.com/

我的测试验证可以从购物车中添加和删除产品。

我写了一个没有参数的方法,如下所示:

public AllProductPage chooseProduct() {
        //Click on product iPhone5
        driver.findElement(By.className("wpsc_buy_button")).click();
        //Expected: Product "iPhone5" has been opened
    return new AllProductPage(driver);
    }

我需要编写一个带有参数的方法并在测试中选择产品,而不是在我编写的代码中。

@Test
    public void verifyThatBeCanAddAndRemoveTheProductFromCart() throws InterruptedException {

        ImplicitWait(driver);

        HomePage onHomePage = new HomePage(driver);
        System.out.println("Step 1");
        AllProductPage onAllProductPage = onHomePage.clickOnAllProduct();
        System.out.println("Step 2");
        onAllProductPage.chooseProduct();
        onAllProductPage.buttonGoToCheckout();
        onAllProductPage.submitForm();
        System.out.println("Step 3");
        Assert.assertTrue(onAllProductPage.getMessage().contains("Oops, there is nothing in your cart."));
    }

我不知道你想传递给函数什么样的数据,但你可以尝试传递一个包含产品名称的字符串,如下所示:

public AllProductPage chooseProduct(String productName) {
    //Click on product received in parameter
    driver.findElement(By.xpath("//div[contains(@class,'productcol')][descendant::*[contains(text(),'"+productName+"')]]//input[@class='wpsc_buy_button']")).click();
    //Expected: Product has been opened
    return new AllProductPage(driver);
}

您的测试可能如下所示:

    @Test
    public void verifyThatBeCanAddAndRemoveTheProductFromCart() throws InterruptedException {

        ImplicitWait(driver);

        HomePage onHomePage = new HomePage(driver);
        System.out.println("Step 1");
        AllProductPage onAllProductPage = onHomePage.clickOnAllProduct();
        System.out.println("Step 2");
        onAllProductPage.chooseProduct("iPhone 5");
        onAllProductPage.buttonGoToCheckout();
        onAllProductPage.submitForm();
        System.out.println("Step 3");
        Assert.assertTrue(onAllProductPage.getMessage().contains("Oops, there is nothing in your cart."));
    }

请注意,在此示例中,产品在测试代码中是固定的,但它也可以是变量。