gpt4 book ai didi

unit-testing - 如何在带有模拟域的grails单元测试中测试默认排序

转载 作者:行者123 更新时间:2023-12-02 14:05:09 25 4
gpt4 key购买 nike

是否可以测试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

}

Grails版本为1.3.1

最佳答案

在我所知道的单元测试中,没有什么好方法可以测试实际排序。您要测试的内容实际上是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
}
}
}

关于unit-testing - 如何在带有模拟域的grails单元测试中测试默认排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3659935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com