Nullpointer in simple grails controller unit test
grails, unit-testing
Solution
the problem most likely is you are using
import grails.transaction.Transactional
instead of
import org.springframework.transaction.annotation.Transactional
for `@Transactional` annotation in the groovy class.
why, no clear answer as to the major difference or why the test doesn't do well with this. Also this usually only happens if you are testing a class with 2 more class layers behind it.
Problem
I need a little assistance with a strange issue I am facing unit testing a very basic Grails 2.4.1 controller. Given this controller: ``` class AuthenticationEventController { def index() { // Sorry, ajax only! if(!request.xhr) { redirect(controller: "main") return false } render(template: "index") return } } ``` And this test: ``` @TestFor(AuthenticationEventController) class AuthenticationEventControllerSpec extends Specification { void "Test that the index rejects non-ajax calls"() { given: request.isXhr = { false } when: controller.index() then: response.redirectedUrl == '/main' } } ``` I get a NullPointerException on the "controller.index()" call. ``` java.lang.NullPointerException at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:130) at org.codehaus.groovy.grails.orm.support.GrailsTransactionTemplate.execute(GrailsTransactionTemplate.groovy:85) at au.com.intrinsicminds.advansys.controller.AuthenticationEventControllerSpec.Test that the index rejects non-ajax calls(AuthenticationEventControllerSpec.groovy:17) ```