我有一些(非 Grails-artifact)类,它们通过传递 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被设置为grailsApplication
中的parentContext
beans.registerBeans(applicationContext)
static void initGrailsApplication() {
...
//the setApplicationContext in DefaultGrailsApplication set's the parentContext
grailsApplication.applicationContext = applicationContext
}
所以你可以通过以下方式获取 bean :
defineBeans {
myService(MyService)
}
assert applicationContext.getBean("myService")
assert grailsApplication.parentContext.getBean("myService")
编辑
今天我遇到了同样的问题,我的解决方案是:
@Before
void setup() {
Holders.grailsApplication.mainContext.registerMockBean("myService", new MyService())
}
关于Grails 单元测试 : Accessing defined beans via grailsApplication,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13532417/