2012-08-12 161 views
5

尋找一種方法來模擬某些單元/集成測試中的彈簧安全性。模擬Grails Spring Security登錄用戶

  • 的Grails:V2.1.0
  • Spring Security的核心:V1.2.7.3

控制器有以下幾點:

//some action 
def index(){ 
    def user = getLoggedInUser() 
    render .... 
}... 

private getLoggedInUser(){ 
    return User.get(springSecurityService.principal.id) 
} 

我嘗試了以下等各種方式,但不能看到得到它的工作:

void testSomething(){ 
    def dc = new SomeController() 
    dc.springSecurityService = [ 
      encodePassword: 'password', 
      reauthenticate: { String u -> true}, 
      loggedIn: true, 
      principal: [username:"Bob"]] 
    dc.index() ... assertion.... 

似乎用戶沒有得到創建,不能得到principle.id。任何建議或更好的選擇?

回答

3

我認爲用戶剛剛創建,但沒有保存,這就是爲什麼它沒有ID。

的解決辦法是這樣的:

void testSomething(){ 
    def dc = new SomeController() 
    def loggedInUser = new User(username: "Bob").save() // This way the user will have an ID 
    dc.springSecurityService = [ 
     encodePassword: 'password', 
     reauthenticate: { String u -> true}, 
     loggedIn: true, 
     principal: loggedInUser] 
    dc.index() ... assertion.... 

有一種替代方案:

void testSomething(){ 
    def dc = new SomeController() 
    def loggedInUser = new User(...).save() 
    dc.metaClass.getLoggedInUser = { loggedInUser } 
... 

我會建議一個重構到getLoggedInUser:

private getLoggedInUser(){ 
    return springSecurityService.currentUser 
} 

隨着這一變化,你可以寫:

void testSomething(){ 
    def dc = new SomeController() 
    def loggedInUser = new User(...).save() 
    dc.springSecurityService = [ 
     encodePassword: 'password', 
     reauthenticate: { String u -> true}, 
     loggedIn: true, 
     getCurrenUser: { loggedInUser }] 
... 
+0

乾杯。 :) – DanyZift 2012-08-13 09:01:31

相關問題