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)
Hence, Grails provides many ways to making testing easier from low level unit testing to high level functional tests. This section details the different capabilities that Grails offers for testing. The first thing to be aware of is that all of the create-* and generate-\* commands create unit or integration tests automatically.
Unit tests are typically run without the presence of physical resources that involve I/O such as databases, socket connections or files. This is to ensure they run as quick as possible since quick feedback is important. Since Grails 3.3, the Grails Testing Support Framework is used for all unit tests. This support provides a set of traits.
The Grails team discourages the embedding of core application logic inside controllers, as it does not promote reuse and a clean separation of concerns. A controller’s responsibility should be to handle a request and create or prepare a response. A controller can generate the response directly or delegate to a view.
Using Grails' interactive mode confers some distinct advantages when executing tests. First, the tests will execute significantly faster on the second and subsequent runs. Second, a shortcut is available to open the HTML reports in your browser: You can also run your unit tests from within most IDEs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With