[英]How do you mock out a static method of a domain object in Grails?
有一個Grails域對象,它有一個自定義靜態函數來從數據庫中獲取數據
class Foo {
/* member variables, mapping, constraints, etc. */
static findByCustomCriteria(someParameter, List listParameter) {
/* code to get stuff from the database... */
/*
Return value is a map
["one": "uno", "two": "due", "three": "tre"]
*/
}
}
靜態函數findByCustomCriteria
使用createCriteria()
來構建從Foo表中提取數據的查詢,這意味着mockDomain(Foo)
在單元測試時無法正常工作。 我正在嘗試解決這個問題的方法是使用一種通用的模擬方法來模擬findByCustomCriteria
,但是我無法正確地findByCustomCriteria
語法。
我有一個控制器BarController
,我正在嘗試測試,並且在調用BarController.someFunction()
時會調用Foo.findByCustomCriteria()
。
class BarControllerTest extends ControllerUnitTestCase {
protected void setUp() {
super.setUp()
}
protected void tearDown() {
super.tearDown()
}
void testSomeFunction() {
/* Mocking for Foo goes here */
assertEquals("someValue", controller.someFunction())
}
}
什么是嘲笑這個的方法?
我嘗試過使用new MockFor()
, mockFor()
和metaClass
,但是我無法使用它。
編輯:
每當我試圖嘲笑這個時,我都試着嘲笑它......
Foo.metaClass.'static'.findByCustomCriteria = { someParam, anotherParam ->
["one": "uno", "two": "due", "three": "tre"]
}
我想我最初沒有提供足夠的信息。
我不止一次遇到過這個場景,你需要修改Foo的靜態 metaClass:
Foo.metaClass.'static'.findByCustomCriteria = { someParameter, List listParameter ->
["one": "uno", "two": "due", "three": "tre"]
}
通常我會把它放在測試設置中,所以我不會忘記何時需要應用它。
在Grails 2.0及更高版本中,您可以像這樣使用GrailsMock
類
def mockControl = new GrailsMock(MyDomainClass)
mockControl.demand.static.get() {id -> return null} // Static method
...
mockControl.verify()
看到這里 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.