我有一些(非Grails-artifact)类通过传递grailsApplication对象来访问服务层bean .但是,我无法对以这种方式实现的类进行单元测试.为什么bean不在主上下文中注册?
@TestMixin(GrailsUnitTestMixin)
class ExampleTests {
void setUp() {}
void tearDown() {}
void testSomething() {
defineBeans {
myService(MyService)
}
assert grailsApplication.mainContext.getBean("myService") != null
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码失败了:
org.springframework.beans.factory.NoSuchBeanDefinitionException:没有定义名为'myService'的bean
我想要做的是通过grailsApplication从普通的旧Java类访问服务.这有效,但不适用于单元测试环境.我应该采用不同的方式吗?
class POJO {
MyService myService;
public POJO(GrailsApplication grailsApplication) {
myService = (MyService) grailsApplication.getMainContext().getBean("myService");
}
}
Run Code Online (Sandbox Code Playgroud)
答案是,在GrailsUnitTestMixin保持你的bean ApplicationContext已设置为parentContext在grailsApplication
beans.registerBeans(applicationContext)
static void initGrailsApplication() {
...
//the setApplicationContext in DefaultGrailsApplication set's the parentContext
grailsApplication.applicationContext = applicationContext
}
Run Code Online (Sandbox Code Playgroud)
所以你可以用你的豆子:
defineBeans {
myService(MyService)
}
assert applicationContext.getBean("myService")
assert grailsApplication.parentContext.getBean("myService")
Run Code Online (Sandbox Code Playgroud)
编辑
今天我遇到了同样的问题,我的解决方案是:
@Before
void setup() {
Holders.grailsApplication.mainContext.registerMockBean("myService", new MyService())
}
Run Code Online (Sandbox Code Playgroud)
在我的情况下(grails 2.4.4),接受的解决方案不起作用,但指向正确的方向,这条线工作,因为我的单元测试中mainContext中的bean工厂是OptimizedAutowireCapableBeanFactory
Holders.grailsApplication.mainContext.beanFactory.registerSingleton('myBean', new MyBeanClass())
Run Code Online (Sandbox Code Playgroud)