Nullpointer in a simple grails unit test controller

I need a little help with a strange problem that I came across with unit testing of a very simple 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 in a 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) 
+7
unit-testing grails
source share
3 answers

the problem is most likely you are using

 import grails.transaction.Transactional 

instead

 import org.springframework.transaction.annotation.Transactional 

for @Transactional annotations in the groovy class.

why, there is no clear answer regarding the main difference, or why the test does not succeed. In addition, this usually only happens if you are testing a class with two more class layers behind it.

+23
source share

Are you using a domain class somewhere else in your code? I had the same problem (NPE raised by TransactionTemplate # execute) and the solution was to use @Mock for one of my entities, according to this jira problem: https://jira.grails.org/browse/GRAILS-11045

+4
source share

The following will work with Grails 2.4.1.

Controller:

 // grails-app/controllers/demo/AuthenticationEventController.groovy package demo class AuthenticationEventController { def index() { if(!request.xhr) { redirect(controller: "main") } else { render(template: "index") } } } 

A unit test:

 // test/unit/demo/AuthenticationEventControllerSpec.groovy package demo import grails.test.mixin.TestFor import spock.lang.Specification @TestFor(AuthenticationEventController) class AuthenticationEventControllerSpec extends Specification { void "Test that the index redirects for non-ajax calls"() { when: controller.index() then: response.redirectedUrl == '/main' } void "Test that index renders template for ajax calls"() { given: request.makeAjaxRequest() views['/authenticationEvent/_index.gsp'] = 'my template text' when: controller.index() then: response.contentAsString == 'my template text' } } 

I hope this helps.

0
source share

All Articles