2012-03-24 10 views
0

上のプリンシパルIDを取得できません:は、私はこのようなコントローラーを持っている私のスポックテスト

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

私はスポックに、コントローラ上のコントローラをテストしたいので、私はこのようなテストコードを書いた:

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

} 

同じエラーが発生します。

何が問題になりましたか?

ありがとうございます。

答えて

6

springSecurityServiceを提供するために何もしていないようですので、もちろんnullです(単体テストには依存性注入がありませんので、ユニットテストクラスでは提供されていないものすべてをモックする必要があります)。 setup:で、これは動作するはずの追加:

controller.springSecurityService = [principal: [id: 42]] 
+0

いやに別のエラーですスローを読んだ原因

springSecurityService.getPrincipal() 

に問題を持っていました:そのようなプロパティはありません:クラスのID:java.lang.Integer \t at mnm.schedule.UserController.userprofile(UserController.groovy:33) ' –

+0

私は、私はレベルを逃した。 '42'を' 42L 'に変更する必要があるかもしれません。 –

+0

返事をありがとう。しかしこの場合、エラーが消えても、 'userProfile'メソッドの' def user = User.get(springSecurityService.principal.id) '行は' null'に実行されます。ユーザーオブジェクトが返されません! –

0

を私として、私は、ネストされたクラスを作成しました。 `groovy.lang.MissingPropertyException:私は、それが唯一のもの

class SService { 

    User principal 

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

    User getPrincipal(){ 
     return this.principal 
    } 
} 

Anはその後、そう、あなたのテスト

def setup() { 
    User first = User.findByUsername('admin') ?: new User(
      username: 'admin', 
      password: 'password', 
      email: "[email protected]", 
      lastName: 'First', 
      firstName: 'First').save(flush: true, failOnError: true) 
    SService sservice = new SService() 
    controller.springSecurityService = new SService() 
    controller.springSecurityService.setPrincipal(first) 
} 
関連する問題