grails - Grails动态查找器,其中字段名称包含保留字

标签 grails groovy hql

所以我有一个grails域类:

class Message
{
    Inbox inbox
    Boolean hasBeenLogicallyDeletedByRecipient
    ...

    static belongsTo = [
        inbox:Inbox,
        ...
    ]

    static constraints = {
        hasBeenLogicallyDeletedByRecipient(nullable:false)
        ...
    }
}

我想使用动态查找器,如下所示:
def messages = Message.findAllByInboxAndHasBeenLogicallyDeletedByRecipient(
                    inbox, false, [order:'desc',sort:'dateCreated'])

在Grails 1.2.1上运行STS 2.6.0.M1中的单元测试用例,可以很好地工作;
旋转Web应用程序,由于在hasBeenLogicallyDeletedByRecipient中的By(我猜它在构建查询时混淆了动态查找器解析)而失败。

我可以使用在应用程序中有效的条件构建器:
    def messages = Message.withCriteria {
        and {
            eq('inbox', inbox)
            eq('hasBeenLogicallyDeletedByRecipient', false)
        }
        order('dateCreated', 'desc')
    }

但是由于withCriteria没有被模拟,因此它不能立即在单元测试中工作,因此我可以在单元测试中添加以下内容:
    Message.metaClass.static.withCriteria = { Closure c ->
        ...
    }

标准/单元测试是否 mock 了最佳/可接受的方法?我对此完全不满意,因为它回避了测试条件关闭的过程。

理想情况下,我宁愿使用动态查找器-是否有一种简洁的方法可以使它按原样工作?
如果没有办法解决,我想可以更改字段名称(有一个原因我不想这样做,但这与问题无关)...

更新:

这是当我尝试在应用程序内部使用findAllByInboxAndHasBeenLogicallyDeletedByRecipient()时的堆栈跟踪-请注意它看起来如何获取最后一个By,并将它与findAll之间的所有其他内容视为属性。我在http://grails.org/OperatorNamesInDynamicMethods上吃草,但没有提及被ver杀。
org.codehaus.groovy.grails.exceptions.InvalidPropertyException: No property found for name [byInboxAndHasBeenLogicallyDeleted] for class [class xxx.Message]
    at xxx.messages.yyyController$_closure3.doCall(xxx.messages.yyyController:53)
    at xxx.messages.yyyController$_closure3.doCall(xxx.messages.yyyController)
    at java.lang.Thread.run(Thread.java:662)

最佳答案

测试数据库查询实际上是一个集成测试,而不是一个单元测试。您的测试是在/ test / unit还是/ test / integration中? -我希望'withCriteria'在集成测试中能完全起作用,但在单元测试中却不能。

在grails文档(http://grails.org/doc/latest/)中,第9.1节:

Unit testing are tests at the "unit" level. In other words you are testing individual methods or blocks of code without considering for surrounding infrastructure. In Grails you need to be particularity aware of the difference between unit and integration tests because in unit tests Grails does not inject any of the dynamic methods present during integration tests and at runtime.

关于grails - Grails动态查找器,其中字段名称包含保留字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4846451/

相关文章:

grails - 在Intellij IDEA中重新创建Grails项目

sql - 使用p6spy插件配置进行Grails 2.0.4和sql性能分析

groovy - 在 Groovy 中更改 map 中的值

java - 在实体类的多个字段上使用 HQL select 语句将 java.lang.object 转换为自定义对象的最佳方法

java - WEB-INF 中资源的奇怪之处

javascript - Grails:AJAX onSuccess方法未触发

java - 重载方法的 Groovy 单元测试

java - 如何将此 SQL 查询转换为 Hibernate 的 HQL?

java - hql查询的返回类型

grails - 使用Grails Fields插件增加f:field(输入)的大小(但不丢失DRY)