HashSet in unit tests

I have a bunch of methods returning a HashSet. I would like my unit test to check the status of these objects. Confirm that someObject.getName() == "foobar".

However, the order of the hashset iterator is not guaranteed, so my unit tests fail several times. How to write block tests for something like this?

For instance:

@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 could accept the answer too soon.

Now the problem is that I implemented the equals method, which only checks for 2 fields in the object for each project (it simulates a database table). However, in my unit test, I want to check all fields, such as description, etc., which do not match my peers. Therefore, if 2 fields are interchanged, and these fields do not coincide with the implementation, then unit test gives a false result.

+5
5

:

public void testRowsToBeRead(){
    HashSet<SomeObject> expectedRows = new HasSet<SomeObject();
    expectedRows.add(new SomeObject("abc"));
    expectedRows.add(new SomeObject("def"));

    HashSet<SomeObject> rows = new SomeObject().read();

    // alternative 1
    assertEquals(19, rows.size());

    for(SomeObject r:rows){
        if (!expectedRows.contains(r)) {
            // test failed
        }
    }

    // alternative 2
    assertTrue(expectedRows.equals(rows));
}

, , , SomeObject equals hashCode , ...

, equals, :

public void testRowsToBeRead(){
    HashSet<SomeObject> expectedRows = new HasSet<SomeObject();
    expectedRows.add(new SomeObject("a", "a1"));
    expectedRows.add(new SomeObject("b", "b1"));

    HashSet<SomeObject> rows = new SomeObject().read();

    for(SomeObject r : rows) {
        SomeObject expected = expectedRows.get(r); // equals and hashCode must still match

        if (expected == null) {
            // failed
        }

        if (!expected.getField1().equals(r.getField1()) && !expected.getField2().equals(r.getField2())) {
            // failed
        }
    }
}

SomeObject equals : field1:

@Override
public boolean equals(Object other) {
    return this.getField1().equals( ((SomeObject) other).getField1() );
}

, . , ...

+4

LinkedHashSet, .

+2

assertThat:

Assert.assertThat(r.getName(), AnyOf.anyOf(Is.is("foobar1"), Is.is("foobar2"), ...));
+2

Assert.assertEquals() TestNG , , JUnit.

, , , .

+2

HashSet.equals(Object).

JavaDoc :

, ; true. , , ; , false. , containsAll ((Collection) o).

, , "" " 2" .

: HashSet , HashSets .

+1

All Articles