Grails单元测试:通过grailsApplication访问定义的bean [英] Grails unit tests: Accessing defined beans via grailsApplication

查看:85
本文介绍了Grails单元测试:通过grailsApplication访问定义的bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些(非Grails-artifact)类,它们通过传递 grailsApplication 对象来访问服务层bean.但是,我无法对以这种方式实现的类进行单元测试.为什么未在主上下文中注册Bean?

I have some (non-Grails-artifact) classes that access the service layer beans via passing around the grailsApplication object. However I'm having trouble unit testing the classes implemented in this way. Why doesn't the bean get registered in the main context?

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

  void tearDown() {}

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

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

上面的代码失败,并显示:

The above code fails with:

org.springframework.beans.factory.NoSuchBeanDefinitionException:未定义名为"myService"的bean

我想做的是通过grailsApplication从普通的旧Java类访问服务.这有效,但是在单元测试环境中不起作用.我应该采取其他方式吗?

What I'm trying to do is access services from plain old Java classes via the grailsApplication. This works, but not in unit test environment. Should I do it differently?

class POJO {
  MyService myService;

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

推荐答案

答案是,在GrailsUnitTestMixin中,将保存您的bean的applicationContext设置为grailsApplication

The answer is that in the GrailsUnitTestMixin the applicationContext that holds your beans is set as the parentContext in the grailsApplication

beans.registerBeans(applicationContext)

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

因此,您可以使用以下方法获得豆子:

So you can get your beans with:

defineBeans {
  myService(MyService)
}

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

编辑

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

Today I faced the same problem, and my solution is:

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

这篇关于Grails单元测试:通过grailsApplication访问定义的bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆