I have a bunch of methods returning HashSet. I would like my unit test to check the state of these objects i.e confirm that someObject.getName() == "foobar".
However the hashset iterator order is not guaranteed so my unit tests fail some times. How do I write unit tests for something like this?
Eg:
@Test
public void testRowsToBeRead(){
HashSet<SomeObject> rows = new SomeObject().read();
assertEquals(19, rows.size());
for(SomeObject r:rows){
//How do I confirm contents?
}
}
I think I might have accepted an answer too soon.
The problem I now have is that I have implemented the equals method, which checks only for 2 fields in the object per design (it is mimicking a DB table).
However in my unit test, I want to check for all fields like description etc which is not in my equals. So if 2 of fields get swapped and these fields are not in my equals implementation, then the unit test gives a false positive.
My approach:
To rely on this test you may need other unit tests confirming that
SomeObject‘sequalsandhashCodemethods work as they should be…EDIT based on one of your comments
If you want to check for fields not part of the
equalscontract, you have to iterate through the set:In the above example
SomeObject‘sequalsmay look like this, it only checks forfield1:No question, depending on your concrete use case this may become more complex. Hope this helps…