我有两个数组列表。我需要使用断言来比较它们,但是当我打印数组列表时,一个是垂直的,由 12 个对象组成,另一个是水平的,所有 12 个对象都在同一行。当我比较它们时,我得到了一个异常(exception)。其中一个列表包含从网站提取的时间值,另一个列表是我创建的数组列表,它根据当前时间递增 2 小时。两个列表应该匹配。但是,我不明白这里有什么错误。理想情况下,我根据本地时间创建的数组列表应该与我从网站上提取的垂直列表相匹配。感谢任何帮助,谢谢!
完整代码如下:
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.text.SimpleDateFormat;
import java.util.*;
public class TestScenario extends BasePage {
@Test
public void testOne() throws InterruptedException {
// Navigate to website
navigateToUrl("https://www.darksky.net/");
ArrayList timeNow = new ArrayList();
// Create list of WebElements returned by xpath
List<WebElement> elements = getDriver().findElements(By.xpath("//*[@id=\"timeline\"]/div/div[3]"));
// For loop to print list of elements
for (WebElement s1 : elements) {
timeNow.add(s1.getText().toUpperCase());
}
// Date format to print time in hours and AM/PM
SimpleDateFormat sdf = new SimpleDateFormat("ha");
String time = sdf.format(Calendar.getInstance().getTime());
// Calendar object to return date
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
// Array created for expected time values
ArrayList timeExpected = new ArrayList();
timeExpected.add("NOW");
// Do while loop to add 2 hours to current time 12 times (24hrs) which is returned from calendar object
int addHours = 2;
int counter = 0;
do {
cal.add(Calendar.HOUR_OF_DAY, addHours);
counter += 1;
timeExpected.add(sdf.format(cal.getTime()));
} while (counter < 11);
// For loops to print all time expected results added to array from do while loop
System.out.println(timeNow);
System.out.println(timeExpected);
Assert.assertEquals(timeNow, timeExpected);
}
这是输出:
[NOW
5AM
7AM
9AM
11AM
1PM
3PM
5PM
7PM
9PM
11PM
1AM]
[NOW, 5AM, 7AM, 9AM, 11AM, 1PM, 3PM, 5PM, 7PM, 9PM, 11PM, 1AM]
java.lang.AssertionError: lists don't have the same size expected [12] but found [1]
Expected :12
Actual :1
最佳答案
问题是
List<WebElement> elements = getDriver().findElements(By.xpath("//*[@id=\"timeline\"]/div/div[3]"));
仅返回一个元素:
NOW
5AM
7AM
9AM
11AM
1PM
3PM
5PM
7PM
9PM
11PM
1AM
所以尝试改变你的分离条件。
关于java - 需要比较两个 ArrayList,但不断遇到异常,因为其中一个正在水平打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48558891/