繁体   English   中英

Grails 单元测试:通过 grailsApplication 访问定义的 bean

[英]Grails unit tests: Accessing defined beans via grailsApplication

我有一些(非 Grails 工件)类通过传递grailsApplication对象来访问服务层 bean。 但是,我在对以这种方式实现的类进行单元测试时遇到了麻烦。 为什么 bean 没有在主上下文中注册?

@TestMixin(GrailsUnitTestMixin)
class ExampleTests {
  void setUp() {}

  void tearDown() {}

  void testSomething() {
    defineBeans {
      myService(MyService)
    }

    assert grailsApplication.mainContext.getBean("myService") != null
  }
}

上面的代码失败了:

org.springframework.beans.factory.NoSuchBeanDefinitionException: 没有定义名为“myService”的 bean

我想要做的是通过 grailsApplication 从普通的旧 Java 类访问服务。 这有效,但不适用于单元测试环境。 我应该以不同的方式做吗?

class POJO {
  MyService myService;

  public POJO(GrailsApplication grailsApplication) {
    myService = (MyService) grailsApplication.getMainContext().getBean("myService");
  }
}

答案是在GrailsUnitTestMixin中,保存 bean 的 applicationContext 被设置为grailsApplicationparentContext

beans.registerBeans(applicationContext)

static void initGrailsApplication() {
...
//the setApplicationContext in DefaultGrailsApplication set's the parentContext
grailsApplication.applicationContext = applicationContext
}

所以你可以得到你的豆子:

defineBeans {
  myService(MyService)
}

assert applicationContext.getBean("myService")
assert grailsApplication.parentContext.getBean("myService")

编辑

今天我遇到了同样的问题,我的解决方案是:

@Before
void setup() {
  Holders.grailsApplication.mainContext.registerMockBean("myService", new MyService())
}

在我的情况下(grails 2.4.4),接受的解决方案不起作用,但为我指明了正确的方向,这条线起作用了,因为我的单元测试中 mainContext 中的 bean 工厂是OptimizedAutowireCapableBeanFactory

Holders.grailsApplication.mainContext.beanFactory.registerSingleton('myBean', new MyBeanClass())

我花了一些时间来解决同样的问题,在我的情况下运行 grails 2.2.4 并具有(在 src/groovy 中):

import grails.util.Holders
class SomeClass {
  transient myService = Holders.grailsApplication.mainContext.getBean 'myService'
  .....
}

这与问题作者有点不同,但至少它对来自搜索引擎结果的人有用

尽管如此,接受的答案对我不起作用,所以我想出了一些不同的模拟和注册 SomeClass 中使用的服务的方法。

import grails.util.Holders
.. other imports
@TestMixin(GrailsUnitTestMixin)
class SomeClassTests {
    @Before
    void setUp() {
        Holders.grailsApplication = grailsApplication
        defineBeans {
            myService(MyServiceMock)
        }
    }
    ....
}

class MyServiceMock extends MyService {
  // overriden methods here
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM