【问题标题】:Grails Unit Testing: Mocking ApplicationContextGrails 单元测试:模拟 ApplicationContext
【发布时间】:2015-01-11 17:04:57
【问题描述】:

我在 grails 类中有以下代码段:

 import org.springframework.context.ApplicationContext;
 import org.codehaus.groovy.grails.web.context.ServletContextHolder
 import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes

    ApplicationContext ctx = (ApplicationContext)ServletContextHolder.servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);

        def contentfulContentDeliveryService =   ctx.getBean('contentfulContentDeliveryService')

当我运行单元测试时,我收到如下错误:

java.lang.NullPointerException: Cannot invoke method getAttribute() on null object

如何模拟这个?

【问题讨论】:

  • 你想测试什么?控制器或其他东西(服务,域类..)?我问是因为 servletContext 被注入到控制器中,这样可能更容易模拟..
  • 这些行存在于 grails 项目的 groovy 源文件中。此类是从服务访问的。我需要为此服务编写测试。

标签: unit-testing grails mocking


【解决方案1】:

通过在resources.groovy 中注册并定义manual 中讨论的bean 引用,将contentfulContentDeliveryService 直接注入到您的类中怎么样?

类似:

myBean(MyClass) {
    contentfulContentDeliveryService = ref("contentfulContentDeliveryService")
}

然后你的类中就会有一个简单的属性,并且可以像任何普通属性一样模拟它。

【讨论】:

    【解决方案2】:

    我找到了办法。我在单元测试文件中添加了以下几行。

    import org.springframework.mock.web.MockServletContext
    import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
    import org.codehaus.groovy.grails.web.context.ServletContextHolder
    
    @TestFor(BannedWordsService)
    class BannedWordsServiceTests {
    
        @Before
        void setUp(){
    
            def servletContext = new MockServletContext()
            servletContext.setAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT, mainContext)
            ServletContextHolder.setServletContext(servletContext) 
        -
    
        -
    
        } 
    
    
     }
    

    现在当我运行单元测试时,我收到如下错误:

      org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'contentfulContentDeliveryService' is defined
    

    我怎样才能模拟那条线?

    【讨论】:

    • 你忘了def mainContext = new MockApplicationContext()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多