Grails 测试工厂类

标签 grails testing integration-testing

鉴于我是 grails 的新手,我正在尝试测试工厂类。 Factory 类位于 src 文件夹中,因为我不希望它作为服务。

class UserFactory {

static Map userDefaults = [
        email           : 'usermail@test.it',
        alias           : 'myalias',
        firstName       : 'Antonio',
        lastName        : 'Roma',
        password        : 'asdhjs',
        placeOfBirth    : 'Milan',
        placeOfResidence: 'Berlin',
        dateOfBirth     : new Date() - 4000
]

static User build(Map properties, Map options = [persisted: true]) {
    userDefaults.putAll properties
    def user = new User(userDefaults)

    if (options.persisted) { user.save() }

    return user
}

static Collection<User> build(Collection<Map> properties, Map options = [persisted: true]) {
    properties.collect { build(it, options) }
}

我想测试是否通过 GORM 正确创建和存储了用户。这里是集成测试:

@TestMixin(DomainClassUnitTestMixin)
class UserFactoryIntegrationSpec extends Specification {

def setup() {
    mockDomain(User)
}

def cleanup() {
}

void "create user"() {
    when:
    User user = UserFactory.build([alias: 'xx', email: 'xx@gmail.com'])

    then:
    User.count() == 1
    user.alias == 'xx'
    user.email == 'xx@gmail.com'
    user.id != null
}

void "create users"() {
    when:
    Collection<User> users = UserFactory.build([[alias: 'xx', email: 'xx@gmail.com'], [alias: 'yy', email: 'yy@gmail.com']])

    then:
    users.size() == 2
    users.alias == ['xx', 'yy']
    users.email == ['xx@gmail.com','yy@gmail.com']
    users.id != [null, null]
}

用户未存储,我猜 GORM 未正确加载...我是否缺少一些注释?!这里是测试应用程序集成的结果:UserFactoryIntegrationSpec

User.count() == 1
     |       |
     0       false

users.id != [null, null]
|     |  |
|     |  false
|     [null, null]
[rigel.resources.User : (unsaved), rigel.resources.User : (unsaved)]

最佳答案

你的开头这么高:

I want to test if the users are created and stored properly through GORM. Here the integration test:

但随后一切都变得一团糟,因为您使用的单元测试假装是集成测试,更糟糕的是,您正在使用单元测试测试持久性。

使用集成测试来测试持久性。仅当单元测试对您正在测试的内容有意义时才使用域类模拟,并且您希望强制域层以某种方式响应,以便您可以专注于 Controller /服务/等。正在测试中。

使用集成测试,它至少配置一个 H2 数据库,具有完整的 ACID 支持、行锁定、真正的 SQL 查询等。如果您愿意,可以将其切换为测试 Oracle 模式、MySQL 数据库等。但是您的测试运行真实的查询和更新。如果您使用模拟来测试持久性,那么您实际上只是在测试模拟。

集成测试不使用混合、模拟等。有一个真正的 Spring ApplicationContext、Hibernate(或您正在使用的任何 GORM)、加载插件等。使用 JUnit 3(扩展 GroovyTestCase) 或 JUnit 4(无基类,使用 JUnit 注释)或 Spock。请注意,集成测试将每个测试运行配置为在一个事务中发生,并且在成功测试结束时或在测试失败时更早回滚,但无论哪种情况,测试之间都没有结转。

如果您想使用 Spock(并且您应该),则扩展 grails.test.spock.IntegrationSpec 以获取默认为 Spock 测试的较新版本的 Grails。在旧版本中,安装 spock 插件并使用插件的集成基类。

关于Grails 测试工厂类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26533105/

相关文章:

java - 如何使用实际数据库进行集成测试?

c# - 在 C# 中测试 Environment.Exit()

spring - 使用Grails渲染插件时无接线 bean

hibernate - 单向一对多

spring - 如何在Grails中搜索多个数据库

c++ - 使用 TDD 的 Ogre 游戏编程

Grails Mail 插件 - 发送空邮件时使用默认内容的正确方法是什么?

android - 如何使用 ActivityInstrumentationTestCase2 捕获异常?

ruby-on-rails - 第一次尝试 RSepc 但没有成功

ruby-on-rails - 对 http header 进行集成测试的弃用警告