I am working on a Grails tutorial from InfoQ called Getting Started With Grails, Second Edition, and I'm trying to add my own codec to the unit test. My environment is Grails 1.3.7 and Groovy 1.7.8.
So, the codec is SHACodec.groovy, and it lives in grails-app / utils. Content:
import java.security.MessageDigest
class SHACodec{
static encode = {target->
MessageDigest md = MessageDigest.getInstance('SHA')
md.update(target.getBytes('UTF-8'))
return new String(md.digest()).encodeAsBase64()
}
}
The codec works fine when I enter the application. It is used for the password field in my UserController.authenticate ()
def authenticate = {
def user =
User.findByLoginAndPassword(params.login, params.password.encodeAsSHA())
if(user){
session.user = user
flash.message = "Hello ${user.login}!"
redirect(controller:"race", action:"list")
}else{
flash.message = "Sorry, ${params.login}. Please try again."
redirect(action:"login")
}
}
When I add this to the unit test, the following error appears:
There is no such property: SHACodec for the class: racetrack.UserControllerTests groovy.lang.MissingPropertyException: There is no such property: SHACodec for the class: racetrack.UserControllerTests at racetrack.UserControllerTests.testAuthenticate (UserControllerTests.groovy: 39)
Test:
package racetrack
import org.codehaus.groovy.grails.plugins.codecs.*
import grails.test.*
class UserControllerTests extends ControllerUnitTestCase {
protected void setUp() {
super.setUp()
String.metaClass.encodeAsSHA = {->
SHACodec.encode(delegate)
}
}
protected void tearDown() {
super.tearDown()
}
void testAuthenticate(){
def jdoe = new User(login:"jdoe", password:"password".encodeAsSHA())
mockDomain(User, [jdoe])
controller.params.login = "jdoe"
controller.params.password = "password"
controller.authenticate()
assertNotNull controller.session.user
assertEquals "jdoe", controller.session.user.login
controller.params.password = "foo"
controller.authenticate()
assertTrue controller.flash.message.startsWith(
"Sorry, jdoe")
}
.
:
SHACodec codec = new SHACodec()
codec.encode("password")
-, unit test.
. ?
!