简体   繁体   中英

Java assert that no two elements are the same in automation test

I'm trying to write a selenium automation test that there are no duplicate elements in an array of elements.

For example there's an array ["Andy", "Bob", "Charles", "David", "David"]

I want to write an automation test that asserts that there are no duplicate names displayed. The following doesn't seem to work very well...

assertThat(getArray(), is(not(getArray())));

How would I write my assertion statement to check each item within the array to make sure there are no duplicates?

Convert your array into a set:

Set mySet = new HashSet(Arrays.asList(someArray));

Then assert that mySet.size() == someArray.length . Turning the array into a set will collapse the duplicates, which reduces the size; if the size has been reduced, you know that there are duplicates.

One more solution. Assuming "names" is your array. As add() will return false if the item will be non-unique:

Set tempSet = new HashSet();
for (String str : names) {
   assertTrue(tempSet.add(str));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM