Unit testing Grails单元测试:模拟ApplicationContext

Unit testing Grails单元测试:模拟ApplicationContext,unit-testing,grails,mocking,Unit Testing,Grails,Mocking,我在grails类中有以下代码段: import org.springframework.context.ApplicationContext; import org.codehaus.groovy.grails.web.context.ServletContextHolder import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes ApplicationContext ctx = (Ap

我在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

我怎么能嘲笑这个呢?

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

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

如何模拟这一行?

如何通过在
resources.groovy
中注册
contentfulContentDeliveryService
并定义一个bean引用(如中所述),将其直接注入类中

比如:

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

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

您想测试什么?控制器或其他东西(服务、域类..)?我这样问是因为servletContext被注入到控制器中,这样可能更容易模拟..这些行出现在grails项目的groovy源文件中。此类是从服务访问的。我需要为此服务编写测试。您忘记了
def mainContext=new MockApplicationContext()