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

リアルまたはモックを提供するために何もしていないように見える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 に答える