0

我有一个这样的控制器:

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

我想在spock中测试控制器上面的控制器,所以我写了这样的测试代码:

def 'userProfile test'() {

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

        when:
        controller.userprofile()

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

当我运行测试时,此测试失败并显示以下错误消息:

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

在集成测试的情况下:

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"
    } 

}

我也得到同样的错误。

什么地方出了错?

提前致谢。

4

2 回答 2

6

您似乎没有做任何事情来提供 real 或 mock springSecurityService,所以它当然是 null (单元测试中没有依赖注入;您必须模拟单元测试类未提供的所有内容)。添加这个setup:应该可以工作:

controller.springSecurityService = [principal: [id: 42]]
于 2012-03-24T04:57:01.253 回答
0

至于我,我创建了嵌套类。我确实有问题

springSecurityService.getPrincipal()

因为它是只读的

class SService {

    User principal

    void setPrincipal(User user){
        this.principal = user
    }

    User getPrincipal(){
        return this.principal
    }
}

然后在你的测试中

def setup() {
    User first = User.findByUsername('admin') ?: new User(
            username: 'admin',
            password: 'password',
            email: "first@email.com",
            lastName: 'First',
            firstName: 'First').save(flush: true, failOnError: true)
    SService sservice = new SService()
    controller.springSecurityService = new SService()
    controller.springSecurityService.setPrincipal(first)
}
于 2016-04-27T09:27:23.053 回答