Possible Bug with using groovy maps for mocking via "as <someClass>" when you are mocking a Map?

StackOverflow https://stackoverflow.com/questions/22679620

  •  22-06-2023
  •  | 
  •  

سؤال

i ran into something really whacky that i think is a bug:

I like using Maps with closures to mock out classes in my unit tests. Recently I tried mocking a Quartz class that implemented Map. I get very strange behavior which i narrowed down to a very simple unit test that just tries to mock out the java.util.Map interface.

the unit test is below. If you run it you will noticed the get() against my abbreviated version of the java.util.Map interface works (MyMap). But when i mock against Map, it fails. I can't figure out why.. and before i file a bug i figured i'd ask my fellow groovy fans. thanks in advance for your input - / chris

package foo

import org.testng.annotations.Test
/*
 * Author: cbedford
 * Date: 3/26/14
 * Time: 4:36 PM
 */

public class GroovyMockTest {

    @Test(enabled = true)
    public void testMapFails() {
    Map map = [
        get: { Object key ->
            println "getting key: " + key
            return 300;
        }

    ] as Map

    assert map.get('dummy') == 300
    }

    @Test(enabled = true)
    public void testMyMapFWorks() {
    MyMap map = [
        get: { Object key ->
            println "getting key: " + key
            return 300;
        }

    ] as MyMap

    assert map.get('dummy') == 300
    }
}

public interface MyMap<K,V> {
    V get(Object key);
}
هل كانت مفيدة؟

المحلول

I doubt this is a bug. Groovy map implements getAt/getProperty/propertyMissing on getting properties from a map, and calling Map::get won't trigger it, because that method exists.

It works if you get the key first and then use it as a closure:

assert map.get('get')('dummy') == 300

Or:

assert map['get']('dummy') == 300
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top