2012-02-15 71 views
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; 
    } 
} 

回答

1

我認爲問題是,你混合集成測試和單元測試。集成測試應該擴展GroovyTestCase,不要使用AST轉換註釋,如TestFor。這通過在我的測試程序:

import grails.validation.ValidationException 

class WorkingServiceTests extends GroovyTestCase { 

    WorkingService workingService 

    void testCreatingNewPlayerWithExistingID() { 

     new Player(platformID: "1").save(flush: true) 

     assert Player.count() == 1 

     shouldFail(ValidationException) { 
     workingService.createNewPlayer("1") 
     } 

     assert Player.count() == 1 
    } 
} 

無關 - 你不應該使用list().size()來從數據庫中獲取的計數,因爲加載每個實例只是爲了獲得數量;改爲使用count()。另外nullable: false是默認值,所以指定它是多餘的。

+0

謝謝,伯特!這是作品!看起來我並不完全瞭解Grails單元測試文檔,必須重新閱讀它。並感謝您提供其他提示。 – Sat 2012-02-16 16:26:35