Unit Testing Web Services - HttpContext

后端 未结 5 833
日久生厌
日久生厌 2021-01-31 00:20

I want to write unit tests for a web service. I create my test project, reference my web project (not service reference, assembly reference), then write some code to test the we

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-31 00:51

    I ended up putting a property on the web service:

    Private mIdentity As System.Security.Principal.IIdentity
    Public Property Identity() As System.Security.Principal.IIdentity
      Get
        If mIdentity Is Nothing Then mIdentity = HttpContext.Current.User.Identity
        Return mIdentity
      End Get
      Set(ByVal value As System.Security.Principal.IIdentity)
        mIdentity = value
      End Set
    End Property
    

    Then in my web service method:

     _
    Public Function GetProject(ByVal projectId As Int32) As String
    
      If Me.Identity.IsAuthenticated Then
    
        'code here
    
      End If
    
    End Function
    

    Then in my test (I'm using RhinoMocks):

    Dim mockery As New MockRepository()
    Dim mockIdentity As System.Security.Principal.IIdentity = mockery.DynamicMock(Of System.Security.Principal.IIdentity)()
    
    Dim projectService As New TeamDynamix.Enterprise.Web.Next.ProjectService()
    projectService.Identity = mockIdentity
    mockIdentity.Stub(Function(i As System.Security.Principal.IIdentity) i.IsAuthenticated).Return(True)
    

提交回复
热议问题