我正在尝试为内容管理系统编写网络驱动程序测试。该测试采用早期测试中创建的不同“文章”,旨在依次检查它们。
这是我的数组:
public static String[] articlesArray = {articleOnePath, articleTwoPath, articleThreePath, articleFourPath,};
...其中“路径”是附加到基本 URL 的相对 URL。
然后我使用 @BeforeClass 设置测试,如下所示: @课前
public static void setup() {
driver = Driver.get();
articlePage = new ArticlePage(driver);
for (String s : articlesArray) {
driver.get(baseURL + s);
articlePage.articlePageHasLoaded();
if(s == null){
System.out.println(s + " could not be found");
}
}
}
然后我运行类似于以下内容的测试断言: @测试 公共(public)无效 twitterShareButtonPresent() {
List<WebElement> twitterShareButton = articlePage.checkTwitterShareButton();
if (twitterShareButton.size() == 0) {
fail("No Twitter share button was found on the page!:" + " " + baseURL + "/" + s);
} else ;
}
问题:
- 如果在之前的测试中未能创建一篇文章(例如articleFour),则articleThreePath 将等于null。当到达 for 循环中的articleThreePath 时,此测试将会失败,并且不会运行articleFour 的测试
- 我需要能够打印到控制台,哪篇文章失败了,但是使用当前的方法(我使用“s”字符串名称),我只得到“null”。
我很高兴可能有更好的方法来做到这一点 - 人们可以提出建议吗?
编辑1:
public static HashMap articlesHashMap = new HashMap<String, String>();
@BeforeClass
public static void setup() {
driver = Driver.get();
articlePage = new ArticlePage(driver);
articlesHashMap.put(articleOneName, articleOnePath);
articlesHashMap.put(articleTwoName, articleTwoPath);
for (articlesHashMap) {
driver.get(baseURL + ??);
if(?? == null){
System.out.println(???);
}
articlePage.articlePageHasLoaded();
}
}
最佳答案
我建议在 Junit 中使用 @Parameterized 来循环不同的页面并运行该测试。这是因为如果没有它,@Before 和 @Test 将仅运行一次。 @Parameterized 表示法将允许您在此测试中获得 4 个不同的结果。这也将更恰本地分离出每个打开页面的 Web 元素引用。
现在看来您将创建一个 articalPage 实例,然后打开 4 个浏览器窗口,然后尝试引用该页面实例的 webElements。如果存在 4 个窗口,selenium 将不知道您正在尝试引用哪一个。您最终要么在最后打开的页面上运行单个测试,要么最终获得过时的 Web 元素引用。
如果您最终确实要处理多个浏览器窗口,您将需要处理它们,以便 selenium 可以引用它们。 Selenium 有一些方法可以做到这一点,例如 .getWindowHandle()、.switchTo() 等。所有这些方法都允许您引用它们并切换焦点。焦点决定了它在何处查找您正在使用的 Web 元素。
关于java - 对多个数组元素执行 JUnit 断言 - 当一个元素失败时如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23609289/