我想我需要在 GebSpec 测试中刷新 hibernate session ,因此我想获取 sessionFactory。
它看起来应该被注入(inject),但是当我做这样的事情时:-
class MySpec extends GebSpec {
def sessionFactory
...
def "test session"(){
....do some setup
then:
assert sessionFactory != null
}
由于 sessionFactory 为空而失败。
最佳答案
我的问题的简短答案是 - 为什么要这样做,这是一个功能测试,并且可能远离正在运行的应用程序 JVM。
原因是因为我想在网络事件发生时检查域对象是否已更新。 Luke Daley 善意地指出,您可以使用远程控制 Grails 插件 ( https://github.com/alkemist/grails-remote-control ) 来做到这一点,这非常酷。安装插件然后就可以了
assert remote {
MyDomainOb.findByName('fred') != null
}
它会发送要在服务器上执行的闭包并返回结果,您可以测试该结果。结果必须是可序列化的。
好的,这是一种方法 - 但是如果由于强加给您的域模型而导致大量复杂的对象在幕后发生变化,那么远程插件要返回测试结果会有点困难。那么,当您位于同一个 JVM 上时,如何做获得测试休眠 session ?像这样:-
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()
我需要更新测试 session ,因此 currentsession.clear() 就是答案。
请注意,如果测试的目标位于单独的虚拟机中,这对您没有帮助,因此您必须使用远程。
关于grails - 如何在 Grails Geb/Spock 测试用例中获取 sessionFactory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6196233/