如何在asp.net mvc 2.0应用程序中测试FormsAuthentication

时间:2010-02-15 14:34:58

标签: asp.net-mvc vb.net forms-authentication xunit

我用以下方法创建了一个界面:

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

我的问题是如何在我的身份验证服务类上测试我的FormsAuthentication。我使用Xunit / Moq写我的测试。当我调用我的操作时,我得到一个“System.NullReferenceException:对象引用未设置为对象的实例”,它告诉我FormsAuthentication对象是Null,因此我无法设置我的身份验证票证。 什么是解决这个问题的最佳解决方案。我会很高兴看到一些代码示例或引用我可以获得灵感的地方。特别是如果解决方案是嘲笑......

1 个答案:

答案 0 :(得分: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作为依赖项(通过构造函数)传递给Authentication类。这将允许您在编写单元测试时模拟IFormsAuthentication调用。 : - )