I'm working through the examples in The Definitive Guide to Grails 2, and all the unit testing is different from the version I am using ( 2.3.7).
What I'm trying to do is test that my register method in the UserController will throw an error if the confirmation password, and password field are not the same. The book gives a test like this
void testPasswordsDoNotMatch() {
request.method = 'POST'
params.login = 'henry'
params.password = 'password'
params.confirm = 'wrongPassword'
params.firstName = 'Henry'
params.lastName = 'Rollins'
def model = controller.register()
def user = model.user
assert user.hasErrors()
assert 'user.password.dontmatch' == user.errors['password'].code
}
So obviously that doesn't work, so I put it together like this:
void "test PasswordsDoNotMatch"() {
given:
params.login='henry'
params.password='password'
params.confirm='wrongPassword'
params.firstName='Henry'
params.lastName='Rollins'
when:
def model = controller.register()
def user = model.user
then:
user.hasErrors()
'user.password.dontmatch' == user.errors['password'].code
}
My UserController looks like this:
package com.gtunes
class UserController {
def register() {
if(request.method =='POST'){
def u = new User(params)
u.properties['login', 'password', 'firstName', 'lastName'] = params
if(u.password != params.confirm){
u.errors.rejectValue("password", "user.password.dontmatch")
return [user:u]
} else if(u.save()) {
session.user = u
redirect controller:"store"
} else {
return[user:u]
}
}
}
}
When I run the test using the command grails> test-app UserController , I get the following error:
Failure: | test PasswordsDoNotMatch(com.gtunes.UserControllerSpec) | java.lang.NullPointerException: Cannot get property 'user' on null object at com.gtunes.UserControllerSpec.test PasswordsDoNotMatch(UserController Spec.groovy:38)
It seems the code I've made doesn't actually create the user in the way I expected, and I'm not sure what I'm doing wrong, or the proper way to test this. I have read through the documentation here: Grails testing, and I'm not sure what I'm missing. Any help is appreciated.