Piotr Gabryanczyk’s Blog

Java, Refactoring, AOP, Spring, DDD, TDD, etc.

  • Blogroll

    • I have joined Anti-IF Campaign

Archive for October, 2007

assertEquals with Map argument !?!?!

Posted by Piotr Gabryanczyk on October 3, 2007

Problem

Have you ever struggled with:
assertEquals(map1, map2) ?

I did! 😦 It is almost impossible to figure out how elements differ, especially if they look the same and are of different type. Or if there is more than 5 of them.

Solution

Print out different elements, i.e.
assertEquals(differenceToString(map1, map2), map1, map2) .

 1     public static String differenceToString(Map m1, Map m2) {
 2         StringBuffer buf = new StringBuffer();
 3         for (Object k : m1.keySet()) {
 4             if (!m2.containsKey(k)) {
 5                 buf.append("M2 does not contain " + k + "\n");
 6             }
 7             if (!m2.get(k).equals(m1.get(k))) {
 8                 buf.append( String.format("m1(%s)=%s,%s != m2(%s)=%s,%s\n", k, m1.get(k), m1.get(k).getClass(), k, m2.get(k), m2.get(k).getClass()));
 9             }
10         }
11         for (Object k : m2.keySet()) {
12             if (!m1.containsKey(k)) {
13                 buf.append("M1 does not contain " + k + "\n");
14             }
15         }
16         return buf.toString();
17     }
18 

Enjoy!:)

Advertisements

Posted in Uncategorized | Tagged: | Leave a Comment »