[英]Grails domain class unsaved in test
我对 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 并且不会抛出错误。
当我正常运行应用程序并在浏览器中手动测试时,整个过程都有效。
我在这里缺少什么? 谢谢您的帮助。
您可能需要使用@Mock([Participation, Person, Event])
注释您的测试类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.