In a jUnit test, I want to get some rows from the database based on the name
column. I then want to test that the rows I got have the names I expected. I have the following:
Set<MyClass> typesToGet = MyClassFactory.createInstances("furniture",
"audio equipment");
Collection<String> namesToGet = Collections2.transform(typesToGet,
new NameFunction<MyClass, String>());
List<MyClass> typesGotten = _svc.getAllByName(typesToGet);
assertThat(typesGotten.size(), is(typesToGet.size()));
Collection<String> namesGotten = Collections2.transform(typesGotten,
new NameFunction<ItemType, String>());
assertEquals(namesToGet, namesGotten); // fails here
I currently get this failure:
java.lang.AssertionError: expected: com.google.common.collect.Collections2$TransformedCollection<[audio equipment, furniture]> but was: com.google.common.collect.Collections2$TransformedCollection<[audio equipment, furniture]>
So what's the cleanest, most concise way to test that I got rows back from the database whose name
column matches the names I said I wanted? I could have a for
loop iterating through and checking that each name in one list exists in the other, but I was hoping to be more concise. Something like the following pseudocode would be nice:
List<MyClass> typesGotten = ...;
["furniture", "audio equipment"].equals(typesGotten.map(type => type.getName()))
You can use containsAll()
two times to check that you don't have any missing value or any unexpected value.
assertTrue(namesToGet.containsAll(namesGotten));
assertTrue(namesGotten.containsAll(namesToGet));
But if you decide to use List
or Set
instead of Collection
, the interface contract specify that a List
is equal to another List
(same for Set
) iff both contains the same values.
Compares the specified object with this list for equality. Returns
true
if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if(e1==null ? e2==null : e1.equals(e2))
.) In other words, two lists are defined to be equal if they contain the same elements in the same order. This definition ensures that the equals method works properly across different implementations of theList
interface.
Resources:
Collection.containsAll()
List.equals()
Set.equals()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With