Alex Rivera | Logout

How to unit test controllers that use springSecurityService?

Asked 2011-12-15T07:58:44.207
9

I have a user class like such:

class User {
    transient springSecurityService
    String displayName
    String password
<snip>
    protected void encodePassword() {
        password = springSecurityService.encodePassword(password)
    }
}

And a UserController. I'm trying to write unit tests for the UserController however I'm getting this error for save, update and delete tests:

java.lang.NullPointerException: Cannot invoke method encodePassword() on null object

What do I have to set up in the way of mocking to get this to work?

I have tried many combinations of mocking code such as the following, but I am at a loss.

defineBeans {
    springSecurityService(SpringSecurityService)
}

Any advice would be greatly appreciated.

Edit
Report

2 Answers

0

I've done that like this:

    protected void encodePassword() {
        // SpringSecutiryService is not injected in tests.
        if (springSecurityService)
            password = springSecurityService.encodePassword(formPassword)
    }
answered 2011-12-15T08:21:05.283
-1

In my case I tried to override SecUser's encodePassword() implementation -which calls springSecurityService.encodePassword().

I was surprised because I needed to override the class and the instance (if I didn't override any, it fails):

SecUser.metaClass.encodePassword = { 'a' }
user.metaClass.encodePassword = { 'b' }

any idea of why do I need this?

answered 2012-08-03T23:21:55.343

Your Answer