2011-06-01 63 views
3

我想我需要在GebSpec測試中刷新休眠會話,所以我想獲得sessionFactory。如何在Grails Geb/Spock測試用例中獲得sessionFactory?

看起來它應注射,但是當我做這樣的事情: -

class MySpec extends GebSpec { 
def sessionFactory 
... 
def "test session"(){ 
....do some setup 
then: 
    assert sessionFactory != null 
} 

失敗與SessionFactory的被空。

回答

5

我的問題的簡短答案是 - 爲什麼你想這樣做,這是一個功能測試,它可能遠離正在運行的應用程序JVM。

原因是因爲我想檢查域對象是否在網絡事件發生時已更新。 Luke Daley善意地指出,你可以使用遠程控制Grails插件(https://github.com/alkemist/grails-remote-control)來實現這一點,這非常酷。你安裝插件然後去

assert remote { 
    MyDomainOb.findByName('fred') != null 
} 

然後它發送該閉包在服務器上執行並返回結果,你可以測試。結果必須是可序列化的。

OK,這是一種方法 - 但如果由於強加於您的域模型而導致許多錯綜複雜的對象在引擎蓋下變化,那麼遠程插件有點難以得到測試結果。那麼當你在同一個JVM上時,你如何獲得測試hibernate會話??像這樣的: -

Session currentSession 

    def setup() { 
     ApplicationContext context = (ApplicationContext) ServletContextHolder.getServletContext().getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT); 
     SessionFactory sf = context.getBean('sessionFactory') 
     currentSession = sf.getCurrentSession() 
    } 

它添加到您的GebSpec的頂部,然後你可以調用currentSession.clear()或currentSession.flush()

我需要有這樣currentsession測試會話更新。 clear()就是答案。

請注意,如果被測試目標位於單獨的虛擬機中,則無法爲您提供幫助,因此您必須使用遠程。

相關問題