无法使用具有 createCriteria() 语句的函数执行单元测试

发布于 2024-10-25 06:01:38 字数 526 浏览 8 评论 0原文

我想编写一个单元测试(通过 JUnit)来测试 Groovy 中该函数的值:

    String getPeopleNamesById(int[] peopleIds) {
        List<String> names = People.createCriteria().list{
            projections { property("name") }
            'in' ("id", peopleIds)
        }
        return names ? names.join(", ") : "";
    }

但是在读取以下语句时单元测试总是失败:List names = People.createCriteria().list{...} groovy.lang.MissingMethodException:没有方法签名:People.createCriteria() 适用于参数类型:() 值:[]。 我猜是因为调用了执行一些数据库连接和查询的函数? 你能帮我写这个测试吗?太感谢了!

I want to write a unit test (by JUnit) to test value of this function in Groovy:

    String getPeopleNamesById(int[] peopleIds) {
        List<String> names = People.createCriteria().list{
            projections { property("name") }
            'in' ("id", peopleIds)
        }
        return names ? names.join(", ") : "";
    }

But the unit test always fails when reading this statement: List names = People.createCriteria().list{...}
groovy.lang.MissingMethodException: No signature of method: People.createCriteria() is applicable for argument types: () values: [].
I guess it because of calling to functions which execute some DB connections and queries?
Could you please help me write this test? Thank you so much!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我喜欢麦丽素 2024-11-01 06:01:38

标准查询在单元测试中不可用,并且 mockDomain 不提供。您可以自己模拟您的条件查询,例如使用 mockFor,或者使您的测试成为集成测试,您可以访问完整的数据库环境。

以下是如何模拟查询的示例:

mockFor(People).demand.static.createCriteria = { ->
    [list: { closure -> [ <some mock objects> ] } ]
}

Criteria queries aren't available in unit tests, and aren't provided by mockDomain. You can either mock your criteria queries yourself, e.g. with mockFor, or make your test an integration test, where you have access to a full database environment.

Here's an example of how you could mock your query:

mockFor(People).demand.static.createCriteria = { ->
    [list: { closure -> [ <some mock objects> ] } ]
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文