我使用具有Page Object模式的Serenity BDD学习测试自动化并为Flickr站点编写测试。
测试用例:当我点击"探索"在主菜单中的链接,页面应包含标签为“photo_title by author”的照片。将鼠标悬停在图像上时,此标签会显示在叠加层中。
这是ExplorePage.class的一部分。运行测试时,我得到NoSuchElementException。
package serenityTest.pages;
import net.serenitybdd.core.pages.PageObject;
import net.thucydides.core.annotations.At;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindAll;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.List;
import static serenityTest.helpers.Waiter.waitForJSandJQueryToLoad;
@At("https://www.flickr.com/explore")
public class ExplorePage extends PageObject {
@FindAll({@FindBy(css = ".title")})
private List<WebElement> photoTitles;
@FindAll({@FindBy(css = ".attribution")})
private List<WebElement> photoAuthors;
@FindAll({@FindBy(xpath = ".//div[@class='view photo-list-photo-view awake']")})
private List<WebElement> photos;
public ExplorePage(WebDriver driver) {
super(driver);
}
public ExplorePage checkPhotoLabels() {
waitForJSandJQueryToLoad();
WebDriverWait waitForPhotos = new WebDriverWait(getDriver(), 10);
waitForPhotos.until(ExpectedConditions.visibilityOfAllElements(photos));
for (WebElement photo : photos) {
for (WebElement photoTitle : photoTitles) {
for (WebElement photoAuthor : photoAuthors) {
withAction().moveToElement(photo).perform();
photoTitle.isDisplayed();
photoAuthor.isDisplayed();
}
}
}
return this;
}
}
也许我以错误的方式测试叠加中的文字。或者定位器存在问题(我尝试了很多变种,包括XPath)。
很乐意提供任何帮助。提前致谢
答案 0 :(得分:0)
逻辑存在缺陷。照片与作者和标题之间存在一对一的映射关系。
使用的嵌套for
循环不正确。当你使用:
for (WebElement photo : photos) {
for (WebElement photoTitle : photoTitles) {
for (WebElement photoAuthor : photoAuthors) {
withAction().moveToElement(photo).perform();
photoTitle.isDisplayed();
photoAuthor.isDisplayed();
}
}
}
你必须检查所有照片作者的所有照片标题为每张照片!!!!
对于10张照片,你的循环功能就像这样...
|Photo#|Title#|Author#|
|1 |1 |1 | <-- Author for-loop starts
|1 |1 |2 |
|1 |1 |... |
|1 |1 |10 |
|1 |2 |1 | <-- Title for-loop increment, Author for-loop restarts
|1 |2 |2 |
|1 |2 |3 |
|1 |... |... |
|1 |2 |10 |
|1 |... |... |
|1 |10 |10 |
|2 |... |... | <-- Photo for-loop increment
|3 |... |... |
正确的for循环是:
for(WebElement photo : photos) {
// Get the index of the photo in the list of photos
int index = photos.indexOf(photo);
// Get the corresponding title of the photo at index from the list of titles
WebElement title = photoTitles.get(index);
// Get the corresponding author of the photo at index from the list of authors
WebElement author = photoAuthors.get(index);
// Always build() actions in order to perform()
withAction().moveToElement(photo).build().perform();
System.out.println("Photo Title is displayed for photo #" + index + "? " + title.isDisplayed());
System.out.println("Photo Author is displayed for photo #" + index + "? " + author.isDisplayed());
}
另外请注意,在使用Actions
时,请确保使用build().perform()
结束链式操作,而不只是perform()
。