Skip to content

Instantly share code, notes, and snippets.

@sujeet100
Created January 13, 2017 06:42
Show Gist options
  • Save sujeet100/cae052b9a2db0ede9efa69ef76c38f7e to your computer and use it in GitHub Desktop.
Save sujeet100/cae052b9a2db0ede9efa69ef76c38f7e to your computer and use it in GitHub Desktop.
Groovy script to find out the difference between two maps. Can be useful to debug failing unit tests when the objects in comparison are big jsons.
def mapDiff(Map m1, Map m2, String path="") { m1.each{k,v->
if(m2[k] != m1[k]) {
if(m1[k] in Map) {
mapDiff(m1[k] as Map, m2[k] as Map, "${path}${k}.")
}
else {
println("${path}${k} ->");
println("\texpected: ${m1[k]}")
println("\tactual: ${m2[k]}")
if (m1[k] in List) {
print("\texpected but missing elements: ")
m1[k].each {
if(!m2[k].any{it1->return it1==it}) {
print(it + ", ")
}
}
print("\tnot expected but found: ")
m2[k].each {
if(!m1[k].any{it1->return it1==it}) {
print(it + ", ")
}
}
}
println("")
}
}
}
}
@eissaeva
Copy link

Hi, I have two questions

  1. what is String path="" parameter?
  2. what is 'k' in m1[k]?
    Is it a specific key in a map that needs to be specified ?

@sujeet100
Copy link
Author

  1. path has a default value of empty string, it is used for recursion. So when you call mapDiff you just need to pass two maps and not worry about path
  2. k in key in the map m1 refer line 1 m1.each{k,v->

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment