WebElement firstItemPrice = driver.findElement(By.className("inventory_item_price"));
WebElement secondItemPrice = driver.findElement(By.className("inventory_item_price"));
// 计算总价
double totalPrice = Double.parseDouble(firstItemPrice.getText().substring(1)) +
Double.parseDouble(secondItemPrice.getText().substring(1));
WebElement total = wait.until(ExpectedConditions.elementToBeClickable(By.className("summary_subtotal_label")));
//WebElement total = driver.findElement(By.className("summary_total_label"));
// 验证总价标签内容
assertEquals(String.format("Item total: $%.2f",+ totalPrice), total.getText());
以上这段代码是通过类名“inventory_item_price”获取页面上的两个元素。findElement
方法(注意这里是单数 "Element")会返回匹配指定条件的第一个元素。这意味着,无论是 firstItemPrice
还是 secondItemPrice
,你实际上都在获取相同的第一个元素。
为了获取具有相同类名的不同元素,需要使用
findElements
(注意这里是复数 "Elements")方法,这将返回一个包含所有匹配元素的列表。
这样的代码获取到的值只能获取到第一个值也就是$29.9,导致最后计算出的预期值是29.9+29.9而并非实际上的$29.9+$9.9
改进后的代码如下
List<WebElement> productPrices = driver.findElements(By.className("inventory_item_price"));
// 获取第一个商品价格
WebElement firstItemPrice = productPrices.get(0);
// 获取第二个商品价格
WebElement secondItemPrice = productPrices.get(1);
// 计算总价
double totalPrice = Double.parseDouble(firstItemPrice.getText().substring(1)) +
Double.parseDouble(secondItemPrice.getText().substring(1));
WebElement total = wait.until(ExpectedConditions.elementToBeClickable(By.className("summary_subtotal_label")));
//WebElement total = driver.findElement(By.className("summary_total_label"));
// 验证总价标签内容
assertEquals(String.format("Item total: $%.2f",+ totalPrice), total.getText());
设定中要获取两个不同的值,因此需要用findElemens将所有匹配元素获取后变成列表(列表索引从0开始)因此第一个元素就是第一个获取到的元素值$29.9,第二个元素就是第二个获取到的元素值$9.9。
测试通过: