WCF服务方法-单元测试和模拟的重构



我有一个WCF服务,它具有以下方法:

Public Function ScheduleEmail(ByVal request As ScheduleEmailRequest) As     ScheduleEmailResponse _
    Implements EmailProtocol.ISchedulingService.ScheduleEmail
    Try
        If Not Email.IsValidEmailAddress(request.EmailAddress) Then
            EmailSchedulerTrace.Source.WriteError(String.Format("Email with template   '{0}' was not sent to '{1}' because it the address is invalid.", request.EmailName, request.EmailAddress))
        Else
            Dim mgr As New JobManager
            Dim job As New EmailJob
            Dim suppression As New SuppressionManager
            Dim emailItem As Email = Email.GetEmailByName(request.EmailName)
            If suppression.CheckSuppresion(emailItem, request.EmailAddress) Then
                job.JobGuid = Guid.NewGuid
                job.EmailAddress = request.EmailAddress
                job.EmailGuid = emailItem.ID
                job.ScheduledSendTime = request.ScheduledTime
                job.CustomAttributes = request.CustomAttributes
                job.ConsumerID = Email.GetConsumerId(request.CustomAttributes)
                mgr.ScheduleJob(job)
            Else
                EmailSchedulerTrace.Source.WriteWarning(String.Format("Email with template '{0}' was not sent to '{1}' because it was suppressed.", request.EmailName, request.EmailAddress))
            End If
        End If
    Catch ex As Exception
        EmailSchedulerTrace.Source.WriteError(ex)
        Throw
    End Try
    Return New ScheduleEmailResponse
End Function

我需要为这个方法编写单元测试。请帮我处理

  • 我需要改变我的方法吗
  • 我该嘲笑什么

非常感谢你的帮助。提前谢谢。当做Sachin

您需要能够交换连接到其他系统(数据库、电子邮件服务器等)的任何"服务"(在方法中new的类或类中的字段),因此您需要为这些类创建interface,并在运行时注入正确的实现。在单元测试中,您可以创建mockfake实现以进行测试。

一个好的开始是定义一个接口:

  • JobManager
  • EmailSchedulerTrace
  • SuppressionManager

您可能还需要在Email 上移动静态方法的功能

  • GetEmailByName
  • GetConsumerId

如果它们封装了数据库访问或任何其他无法隔离的服务。

最新更新