Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 463
  • Last Modified:

Junit assertCollection?

What's the best way to unit test that 2 collections are the same.
(Not the same object, but each element value of one collection is in the other, and vice versa)
0
allelopath
Asked:
allelopath
  • 4
1 Solution
 
for_yanCommented:

Are all objects in your collections unique?
Or you may have two equal options present in any of your two collections?

if they are unique then if the sizes of both collections are equal,
and then you just traverse one collection and check that
all elements of this coll;ection are present in the second collection then
tyour collections are the same in the sense you mentioned
0
 
for_yanCommented:

if my question above has the anser "yes" then this method should work:

boolean areTheyEqual(ArrayList a1, ArrayList a2){
if(a1.size() != a2.size() ) return false;

for(int j=0; j<a1.size(); j++){
if(!a2.contains(a1.get(j)){
return false;
}
}
return true;

}

0
 
for_yanCommented:

I think this should work even if each collection
has identical items:

boolean areTheyEqual(ArrayList a1, ArrayList a2){
if(a1.size() != a2.size() ) return false;
for(int j =0; j<a1.size(); j++){
int count1 = 0;
for(int k=0; k<a1.size(); k++){
if(a1.get(j).equals(a1.get(k))count1++;

}
int count2 = 0;
for(int k=0; k<a2.size(); k++){
if(a1.get(j).equals(a2.get(k))count2++;

}
if(count1 != count2)return false;

}
retrurn true;

}
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
allelopathAuthor Commented:
Thanks.
Looks like I could also use Apache Commons CollectionsUtils
CollectionUtils.isEqualCollection(actual, expected);
0
 
for_yanCommented:
Yes, you are right - that probably would be better.
But it is nice to invent the wheel also :)
0
 
CEHJCommented:
coll1.removeAll(coll2);
boolean identical = coll1.size() == 0;
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now