0
使用Grails 2.0.0我創建的服務創建了Player類的實例並將其保存在數據庫中。然後我編寫JUnit集成測試,檢查服務方法createNewPlayer(String platformID)是否在Player.save(failOnError:true)的約束驗證失敗時拋出異常。失敗的約束驗證後內存中的對象無效
一切順利的罰款,但方法shouldFail(...)如果我來電之後:
assert Player.list().size() == 1;
我得到這個錯誤:
--Output from testCreatingNewPlayerWithExistingID--
| Error 2012-02-15 21:52:05,293 [main] ERROR hibernate.AssertionFailure - an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session)
Message: null id in test1.Player entry (don't flush the Session after an exception occurs)
我的問題是:如何測試在shouldFail方法中拋出異常,以便Hibernate不會在內存中保存無效的Player類的實例,並且在此之後有null ID?
下面我的代碼示例:
class WorkingService
{
Player createNewPlayer(String platformID) throws ValidationException {
Player player = new Player(platformID: platformID);
return player.save(failOnError : true);
}
}
class Player
{
String platformID
static constraints = {
platformID nullable: false, blank: false, unique: true
}
}
@TestFor(WorkingService)
class WorkingServiceTests
{
WorkingService workingService;
void testCreatingNewPlayerWithExistingID()
{
def player = new Player(platformID: "1");
player.save(flush: true);
assert Player.list().size() == 1;
shouldFail ValidationException, {
player = workingService.createNewPlayer("1");
}
assert Player.list().size() == 1;
}
}
謝謝,伯特!這是作品!看起來我並不完全瞭解Grails單元測試文檔,必須重新閱讀它。並感謝您提供其他提示。 – Sat 2012-02-16 16:26:35