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

时间:2017-01-05 00:33:22

标签: selenium selenium-webdriver junit pageobjects

测试此网站: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."));
    }

1 个答案:

答案 0 :(得分:0)

我不知道您希望传递给函数的数据类型,但您可以尝试传递包含产品名称的String,如下所示:

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."));
    }

请注意,在此示例中,产品已在测试代码中修复,但也可能是变量。