我对Grails还是比较陌生,正在构建一个事件管理应用程序。我有一个问题,我的域类之一在调用.save()
方法后没有保存,而仅在测试期间保存。
如此简化,我有3个领域类:人,事件和参与。我遇到的一个问题是参与:
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))
,情况也是如此。因此,当第二次调用e.getParticipants().size()
且未引发错误时,join(...)
为0。
当我正常运行应用程序并在浏览器中手动测试时,整个过程正常工作。
我在这里想念什么?感谢您的帮助。
您可能需要用@Mock([Participation, Person, Event])
注释测试班。