Cannot get principal id on my Spock test

Posted by Ant's on Stack Overflow See other posts from Stack Overflow or by Ant's
Published on 2012-03-24T03:45:47Z Indexed on 2012/03/24 5:29 UTC
Read the original article Hit count: 188

Filed under:

I have a controller like this :

@Secured(['ROLE_USER','IS_AUTHENTICATED_FULLY'])
    def userprofile(){
        def user = User.get(springSecurityService.principal.id)
        params.id = user.id
        redirect (action : "show", params:params)
    }

I want to test the controller above controller in spock, so I wrote a test code like this:

def 'userProfile test'() {

        setup:
        mockDomain(User,[new User(username:"amtoasd",password:"blahblah")])

        when:
        controller.userprofile()

        then:
        response.redirectUrl == "/user/show/1"
    }

When I run my test, this test fails with this error message :

java.lang.NullPointerException: Cannot get property 'principal' on null object
    at mnm.schedule.UserController.userprofile(UserController.groovy:33)

And in case of Integration test:

class UserSpec extends IntegrationSpec {

    def springSecurityService

    def 'userProfile test'() {

        setup:
        def userInstance = new User(username:"antoaravinth",password:"secrets").save()
        def userInstance2 = new User(username:"antoaravinthas",password:"secrets").save()
        def usercontroller = new UserController()
        usercontroller.springSecurityService = springSecurityService

        when:
        usercontroller.userprofile()

        then:
        response.redirectUrl == "/user/sho"
    } 

}

I get the same error as well.

What went wrong?

Thanks in advance.

© Stack Overflow or respective owner

Related posts about spock