代码之家  ›  专栏  ›  技术社区  ›  dstarh

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

  •  2
  • dstarh  · 技术社区  · 14 年前

    有没有可能测试一下 propertyName 定义在 staticMappingBlock ?

    这在集成阶段有效,但在我的域具有以下特性的单元阶段无效:

    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
    
    }
    

    1 回复  |  直到 4 年前
        1
  •  2
  •   Ted Naleid    14 年前

    据我所知,在单元测试中没有任何好的方法来测试实际的排序。您尝试测试的内容实际上是GORM集成的一个组成部分,在模拟的域对象上测试它,即使它们支持排序映射,也不会测试将要运行的实际代码。

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

    我把一个 blog post

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