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

时间:2013-08-02 11:03:50

标签: wcf unit-testing

我使用以下方法进行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

我需要为此方法编写单元测试。

请帮帮我
  • 我需要更改方法中的任何内容吗?
  • 我应该嘲笑什么?

非常感谢您的帮助。提前致谢。 问候, 萨钦

1 个答案:

答案 0 :(得分:0)

您需要能够交换任何'服务'(您在类中的一个或多个方法中new的类)连接到其他系统的数据库(数据库,电子邮件)服务器等)所以你需要为类创建interface并在运行时和单元测试中注入正确的实现,你可以创建mockfake实现用于测试目的。 / p>

一个好的开始是为:

定义一个接口
  • JobManager
  • EmailSchedulerTrace
  • SuppressionManager

您可能还需要在Email

上移动静态方法的功能
  • GetEmailByName
  • GetConsumerId

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