Ale*_*lex 10 grails groovy mocking hibernate-criteria
我可以模拟调用:
MyDomainClass.createCriteria().list{
eq('id',id)
eq('anotherParameter',anotherParameterId)
}
Run Code Online (Sandbox Code Playgroud)
有:
def myCriteria = [
list : {Closure cls -> returnThisObject}
]
MyDomainClass.metaClass.static.createCriteria = { myCriteria }
Run Code Online (Sandbox Code Playgroud)
建议:
http://davistechyinfo.blogspot.com/2010/01/mocking-hibernate-criteria-in-grails.html
但对于:
MyDomainClass.createCriteria().get{
eq('id',id)
eq('anotherParameter',anotherParameterId)
}
Run Code Online (Sandbox Code Playgroud)
这种方法失败了 - 也许是因为'get'是一个'list'的关键字.任何人都可以建议 - 能够在域类中模拟这一点应该是可能的,而不是简单地放弃使用的方法的单元测试覆盖createCriteria().get{}.
建议非常感谢,
亚历克斯
Ale*_*lex 15
我找到了一个不会影响我编写单元测试能力的解决方案 -
def myCriteria = new Expando();
myCriteria .get = {Closure cls -> returnThisObject}
MyDomainClass.metaClass.static.createCriteria = {myCriteria }Run Code Online (Sandbox Code Playgroud)
这正是我想要的,并可能支持测试提供的参数.谢谢你的回应.希望这对其他测试domain/createCriteria()方法的人有用.
我不打扰.而是在您的域类中创建方法并模拟它们.这使测试变得更容易,但更重要的是,它具有将持久性保留在其所属位置而不是将其分散到整个代码库中的优点:
class MyDomainClass {
String foo
int bar
static MyDomainClass findAllByIdAndAnotherParameter(long id, long anotherParameterId) {
createCriteria().list {
eq('id',id)
eq('anotherParameter',anotherParameterId)
}
}
static MyDomainClass getByIdAndAnotherParameter(long id, long anotherParameterId) {
createCriteria().get {
eq('id',id)
eq('anotherParameter',anotherParameterId)
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的测试中,只需将其模拟为
def testInstances = [...]
MyDomainClass.metaClass.static.findAllByIdAndAnotherParameter = { long id, long id2 ->
return testInstances
}
Run Code Online (Sandbox Code Playgroud)
和
def testInstance = new MyDomainClass(...)
MyDomainClass.metaClass.static.getByIdAndAnotherParameter = { long id, long id2 ->
return testInstance
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5715 次 |
| 最近记录: |