【发布时间】: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