帮助Grails测试失败 - 域方法不起作用?

时间:2011-05-06 15:22:49

标签: java unit-testing grails groovy

鉴于此服务:

class AchievementsService {

    static transactional = true

    public void onEvent(String eventName, User user) {
        def event = Event.findByName(eventName)
        if (!event) {
            event = new Event(name: eventName, autoConfigured: true)
            event.save()
        }
    }
}

为什么这个测试失败了:

class AchievementsServiceTests extends GrailsUnitTestCase {
    AchievementsService service
    User user
    protected void setUp() {
        super.setUp()
        service = new AchievementsService()
        user = new User(username:"marty",password: "password")
        mockDomain(User,[user])
    }

    void testThat_given_eventDoesNotExistWhenCallingOnEvent_that_eventIsCreated()
    {
         mockDomain Event       
         service.onEvent "MyEvent", user
         assert Event.count() == 1
    }
}

失败如下:

Assertion failed: 

assert Event.count() == 1
             |       |
             0       false

我必须在我的设置或调用.save()方法时丢失一个步骤,但我看不到它。

1 个答案:

答案 0 :(得分:2)

您可能验证失败,请将此代码添加到您的服务中以打印验证错误:

if (!event.save()) { 
  event.errors.each{println it} 
}