Search code examples
groovymockingcoercion

How to mock a java.util.Map in groovy using map coercion?


I am trying to mock Map using groovy map coercion. I have tried various variations of the code bellow but the result was always null.

Map<String, String> map = [get: {String  k -> "echo"}] as Map<String, String>

println map.get("a")

If I use map = {"echo"} as Map<String, String> it works.

Any ideas on how to make the first version work?

thanks


Solution

  • The problem with doing a straight coercion like that is that the Map that redefines get is already a Map and there's a check in the Groovy source coercion that says if what you're trying to do is coerce something like a Map into a Map then just cast it normally instead of trying to create proxy to the interface as you want.

    To get around this you can make your mock object a different type than Map, like an Expando, then it'll coerce into your interface type:

    Map<String, String> map = new Expando([get: {String  k -> "echo"}]) as Map<String, String>
    assert map.get('a') == 'echo'