10

我可以模拟调用:

MyDomainClass.createCriteria().list{
    eq('id',id)
    eq('anotherParameter',anotherParameterId)
}

和:

def myCriteria = [
    list : {Closure  cls -> returnThisObject}
]
MyDomainClass.metaClass.static.createCriteria = { myCriteria }

如建议:

http://davistechyinfo.blogspot.com/2010/01/mocking-hibernate-criteria-in-grails.html

但对于:

MyDomainClass.createCriteria().get{
    eq('id',id)
    eq('anotherParameter',anotherParameterId)
}

这种方法失败了——可能是因为“get”是一个关键字,而“list”不是。任何人都可以建议 - 能够在域类中模拟这个应该是可能的,而不是简单地放弃使用createCriteria().get{}.

建议非常感谢,

亚历克斯

4

3 回答 3

18

我找到了一个不会影响我编写单元测试能力的解决方案 -

def myCriteria = new Expando();
myCriteria .get = {Closure  cls -> returnThisObject}         
MyDomainClass.metaClass.static.createCriteria = {myCriteria }

这正是我想要的,并且可能支持测试提供的参数。感谢其他回复。希望这对其他测试 domain/createCriteria() 方法的人有用。

于 2010-09-16T09:12:16.183 回答
5

我不会打扰。而是在您的域类中创建方法并模拟这些方法。这使测试更容易,但更重要的是具有将持久性保持在它所属的位置而不是将其分散在整个代码库中的优势:

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)
      }
   }
}

然后在您的测试中,将其模拟为

def testInstances = [...]
MyDomainClass.metaClass.static.findAllByIdAndAnotherParameter = { long id, long id2 ->
   return testInstances
}

def testInstance = new MyDomainClass(...)
MyDomainClass.metaClass.static.getByIdAndAnotherParameter = { long id, long id2 ->
   return testInstance
}
于 2010-09-15T19:46:19.020 回答
1

现在使用GrailsUnitTestCase.mockDomain1方法应该会简单得多。

grails-app/domain/sandbox/grails/foo/Something.groovy

package sandbox.grails.foo

class Something {
    String name
}

测试/单元/沙盒/grails/foo/SomethingTests.groovy

package sandbox.grails.foo

import grails.test.mixin.*
import org.junit.*

@TestFor(Something)
class SomethingTests {

    void testSomething() {

        mockDomain(Something, [
            new Something(name: 'Foo'),
            new Something(name: 'Bar'),
            new Something(name: 'Boo'),
            new Something(name: 'Baz')
        ])

        def actuals = Something.createCriteria().list(sort: 'name', order: 'asc') {
            like('name', '%oo')
        }

        assertEquals 2, actuals.size()

    }
}
于 2011-10-28T09:32:13.277 回答