如何使用模拟域测试grails单元测试中的默认排序

时间:2010-09-07 15:12:10

标签: unit-testing grails

是否可以测试staticMappingBlock

中定义的排序'propertyName'

这适用于整合阶段,但不适用于我的域

的单元阶段
static mapping = {
    sort 'lastName'
}

void testDefaultSortOrder(){
    def agent1 = new CommissionAgent(firstName: 'fred', lastName: 'b', active:true).save()
    def agent2 = new CommissionAgent(firstName: 'fred2', lastName:'a', active:false).save()

    def agents = CommissionAgent.list()
    assertEquals 'sort order is wrong', agents[0].lastName, agent2.lastName
    assertEquals 'sort order is wrong', agents[1].lastName, agent1.lastName

}

Grails版本为1.3.1

1 个答案:

答案 0 :(得分:2)

没有任何好方法可以测试我所知道的单元测试中的实际排序。您尝试测试的内容实际上是GORM集成中不可或缺的一部分,即在它们支持排序映射的情况下对它进行测试,并不测试将要运行的实际代码。

您在单元测试中最接近的事情是查看静态映射对象,断言“sort”的值设置为您期望的值。

前一段时间我把blog post放在一起讨论如何查询值的groovy闭包。此技术可用于断言排序顺序设置为您期望的结果:

Foo域对象:

package com.example

class Foo {

    String name

    static mapping = {
           sort "name"
    }
}

FooTests单元测试:

package com.example

import grails.test.*

class FooTests extends GrailsUnitTestCase {
    void testFooSort() {
         def mappingValues = ClosureInterrogator.extractValuesFromClosure(Foo.mapping)
         assertEquals "name", mappingValues.sort
    }
}

ClosureInterrogator类,允许您查看闭包的作用:

package com.example

class ClosureInterrogator {
    private Map closureValueMap = [:]

    static Map extractValuesFromClosure(Closure closure) {
        def interrogator = new ClosureInterrogator(closure)
        return interrogator.closureValueMap
    }

    private ClosureInterrogator(Closure closure) {
        def oldResolveStrategy = closure.getResolveStrategy()
        def oldDelegate = closure.getDelegate()
        closure.delegate = this
        closure.resolveStrategy = Closure.DELEGATE_FIRST

        try {
            closure()
        } finally {        
            closure.setDelegate(oldDelegate)
            closure.setResolveStrategy(oldResolveStrategy)
        }
    }

    // property getter
    def propertyMissing(String name) {
        return closureValueMap[name]
    }

    // property setter
    def propertyMissing(String name, value) {
        closureValueMap[name] = value
    }

    def methodMissing(String name, args) {
        if (args.size() == 1) {
            closureValueMap[name] = args[0]
        } else {
            closureValueMap[name] = args
        }
    }
}