[英]How to mock static Map property in grails service class unit test
I have a static map in a service class.I am unit testing the method which populates the map. 我在服务类中有一张静态地图,正在对填充地图的方法进行单元测试。 I want to know how to mock the map used in the service class.
我想知道如何模拟服务类中使用的地图。
SomeService
--------------
class SomeService {
static Map<Integer,String> tempMap = new HashMap<Integer,String>()
//This map is used in some other service api
}
OtherService
------------
class OtherService {
void method1(Integer i, String str) {
// here it populates the map
def test = SomeService.tempMap.put(i,str)
println "After putting : "+test
}
}
Unit test case 单元测试用例
OtherServiceTests
------------------
class OtherServiceTests {
void testMethod1() {
def mockedMap = mockFor(Map)
SomeService.metaClass.static.tempMap = mockedMap.createMock()
SomeService.metaClass.static.tempMap.put = {Integer i, String str -> "Testing"} // how to mock??
}
}
When I run the test case it is invoking the real map instead of making use of the mocked "put"
api, which is returning null instead of "testing" I tried couple of ways to mock it but still no luck. 当我运行测试用例时,它调用的是真实地图,而不是使用模拟的
"put"
api,该API返回null而不是“ testing”,我尝试了几种方法对其进行模拟,但仍然没有运气。 How to mock Map api
which is a static
property of a service class? 如何模拟
Map api
,它是服务类的static
属性?
对于嘲笑,您可以尝试
SomeService.tempMap.getClass().metaClass.put = {Integer i, String str -> "Testing"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.