【问题标题】:Grails domain class unsaved in test测试中未保存的 Grails 域类
【发布时间】:2019-12-24 05:04:07
【问题描述】:

我对 grails 比较陌生,正在构建一个事件管理应用程序。我有一个问题,我的一个域类在调用 .save() 方法后没有保存,而只是在测试期间。

如此简化,我有 3 个域类:Person、Event 和 Participation。我遇到的问题是参与:

class Participation implements Serializable {

    private static final long serialVersionUID = 1

    Person person
    Event event

    static Participation create(Person person, Event event, boolean flush = false) {
        def instance = new Participation(person: person, event: event)
        instance.save([failOnError: true, flush: flush])
        instance
    }

    static constraints = {
        person nullable: false
        event nullable: false, validator: { Event e, Participation pt ->
            if (pt.person?.id) {
                if (Participation.exists(pt.person.id, e.id)) {
                    return ['participation.exists']
                }
            }
        }
    }

    static mapping = {
        id composite: ['person', 'event']
        version false
    }
}

我正在尝试测试如果一个人加入一个已经满员的事件会发生什么,这是在服务中处理的:

@Transactional
class UserService {

    def join(Person p, Event e) {
        if (e.getParticipants().size() >= e.maxParticipants) {
            throw new EventFullException()
        }
        Participation.create(p, e)
    }

}

我的测试如下:

class UserServiceSpec extends HibernateSpec implements ServiceUnitTest<UserService>{

    void "a person cannot join a full event"() {
        when:
        Person p1 = save(new Person(name: "Test1"))
        Person p2 = save(new Person(name: "Test2"))
        Event e = save(new Event(name: "Event", start: LocalDateTime.now().plusDays(1), maxParticipants: 1))
        service.join(p1, e)

        then:
        // Participation for some reason not saved ):
        shouldFail(EventFullException) {
            service.join(p2, e)
        }
    }

    private def save(domain) {
        domain.save flush: true, failOnError: true
    }

我看到的是 Event 和 Person 域对象按预期保存,但对于 Participation 对象,(IntelliJ)调试器在它旁边显示“未保存”。如果我直接调用def part = save(new Participation(p1, e)) 也是这种情况。所以第二次调用join(...)e.getParticipants().size()为0,不会抛出错误。

当我正常运行应用程序并在浏览器中手动测试时,一切正常。

我在这里缺少什么?感谢您的帮助。

【问题讨论】:

    标签: testing grails grails-orm


    【解决方案1】:

    您可能需要使用 @Mock([Participation, Person, Event]) 注释您的测试类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多