Reputation: 167
I have the following segment of code in a grails class:
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')
When I run unit tests, I get an error like:
java.lang.NullPointerException: Cannot invoke method getAttribute() on null object
How can I mock this?
Upvotes: 1
Views: 2521
Reputation: 2931
What about directly injecting contentfulContentDeliveryService
into your class by registering it in resources.groovy
and defining a bean reference as discussed in the manual?
Something like:
myBean(MyClass) {
contentfulContentDeliveryService = ref("contentfulContentDeliveryService")
}
Then you would have a simple property in your class and could mock it like any normal property.
Upvotes: 0
Reputation: 167
I found a way. I added the following lines to unit tests file.
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)
-
-
}
}
Now when I run unit tests, I get an error as:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'contentfulContentDeliveryService' is defined
How can I mock that line?
Upvotes: 1