2011-06-01 90 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()就是答案。

请注意,如果被测试目标位于单独的虚拟机中,则无法为您提供帮助,因此您必须使用远程。

相关问题