gpt4 book ai didi

unit-testing - Grails单元测试:模拟ApplicationContext

转载 作者:行者123 更新时间:2023-12-02 14:42:36 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com