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

我该如何 mock ?

最佳答案

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

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

我如何 mock 那条线?

关于unit-testing - Grails单元测试:模拟ApplicationContext,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26927743/

10-13 05:48