Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jUnit and Guava, comparing list equality after transform()

Tags:

java

junit

guava

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()))
like image 573
Sarah Vessels Avatar asked Apr 09 '12 22:04

Sarah Vessels


1 Answers

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 the List interface.


Resources:

  • Javadoc: Collection.containsAll()
  • Javadoc: List.equals()
  • Javadoc: Set.equals()
like image 171
Colin Hebert Avatar answered Nov 12 '22 03:11

Colin Hebert