2010-02-15 103 views
1

伊夫測試FormsAuthentication在asp.net的MVC 2.0應用進行的有以下方法接口:如何使用

Public Interface IAuthenticationService 
    Sub SetAuthentication(ByVal username As String) 
    Sub Logout() 
    Function IsLoggedIn() As Boolean 
End Interface 

我的實現是這樣的:

Public Class Authentication 
    Implements IAuthenticationService 
    Public Sub Logout() Implements IAuthenticationService.Logout 
     FormsAuthentication.SignOut() 
     LoggedIn = False 
    End Sub 

    Public Sub SetAuthentication(ByVal username As String) Implements IAuthenticationService.SetAuthentication 
     FormsAuthentication.SetAuthCookie(username, True) 
     LoggedIn = True 
    End Sub 

    Public Function IsLoggedIn() As Boolean Implements IAuthenticationService.IsLoggedIn 
     If LoggedIn Then Return True 
     Return False 
    End Function 

    Private _isLoggedIn As Boolean = false 
    Public Property LoggedIn() As Boolean 
     Get 
      Return _isLoggedIn 
     End Get 
     Set(ByVal value As Boolean) 
      _isLoggedIn = value 
     End Set 
    End Property 
End Class 

在我的控制器類,我擁有這臺對我的FormsAuthentication票證一個動作:

Public Function Login(ByVal username As String, ByVal password As String) As ActionResult 

     _authenticationService.SetAuthentication(username) 
     Return View() 
    End Function 

我的問題是如何測試我的FormsA認證服務類上的認證。我使用Xunit/Moq寫我的測試。當我調用我的操作時,我得到一個「System.NullReferenceException:對象引用未設置爲對象的實例」,它告訴我FormsAuthentication對象爲Null,因此我無法設置身份驗證票證。 什麼是解決這個問題的最佳解決方案。我會很高興看到一些代碼示例或參考資料,以便我可以獲得一些啓示。特別是如果該解決方案是嘲諷......

回答

3

創建圍繞FormsAuthentication類像這樣的包裝類...

Public Interface IFormsAuthentication 
    Sub SignIn(ByVal userName As String, ByVal createPersistentCookie As Bool) 
    Sub SignOut() 
End Interface 


Public Class FormsAuthenticationWrapper Implements IFormsAuthentication 

    Public Sub SignIn(ByVal userName As String, ByVal createPersistentCookie As Bool) Implements IFormsAuthentication.SignIn 
     FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); 
    End Sub 

    Public Sub SignOut() Implements IFormsAuthentication.SignOut 
     FormsAuthentication.SignOut() 
    End Sub 

End Class 

然後,您可以在您的驗證類通過IFormsAuthentication作爲扶養(通過構造)。這將允許您在編寫單元測試時模擬IFormsAuthentication調用。 :-)

+0

我推薦這個答案。 – Neeta 2013-02-20 11:12:20