下面是我的测试方法,如果一切正常,只需将数据插入数据库。
[TestMethod]
public void PostActivationRequest_Returns_Created_On_Successful_Request()
{
ActivationRequestWM activationRequestWM = new ActivationRequestWM
{
EMail = "unitTest@gmail.com",
ConfirmationTypeID = 1
};
var testResponse = _userController.PostActivationRequest(activationRequestWM);
Assert.AreEqual(HttpStatusCode.Created, testResponse.StatusCode);
}
但是,此PostActivationRequest
也在请求完成之前发送电子邮件。
public void PostActivationRequest(ActivationRequestWM model)
{
//model validation stuff
var activationCode = CreateUniqueActivationCodeForCreateAccount(model.EMail);
var newActivationCodeRequest = new UserActivationRequest
{
EMail = model.EMail,
MobileNumber = model.MobileNumber,
ConfirmationType = model.ConfirmationTypeID,
CreationTime = DateTime.Now,
ActivationCode = activationCode,
IsUsed = false,
IsActive = true,
};
INotification notification;
INotificationBaseModel notificationModel;
switch (model.ConfirmationTypeID)
{
case AccountConfirmationType.SMS:
//SMS sender
break;
default:
notification = NotificationFactory.GetNotification(NotificationType.Mail);
notificationModel = new MailNotificationModel
{
SendTo = model.EMail,
Title = "Activate Your Account",
Message = "Your Verification Code is " + activationCode
};
break;
}
using (TransactionScope transaction = new TransactionScope())
{
try
{
if (previousRequest != null)
{
_userActivationRequestOperations.UpdateUserActivationRequest(previousRequest);
}
_userActivationRequestOperations.InsertUserActivationRequest(newActivationCodeRequest);
notification.Send(notificationModel); //this code triggers e-mail sender
transaction.Complete();
}
catch (DatabaseOperationException)
{
//throw exceptions
}
}
}
实际上,方法很好,因为当我通过Fiddler发送请求时它可以工作。但是,当我调试上述测试方法时,我遇到了client.ServicePoint
的问题,该问题引发了System.InvalidOperationException
类型的异常
我还发现,当我来自测试方法时,SmtpClient的其他一些属性(如Host
,Port
,Credentials
和TargetName
也具有不同的值(即{{ 1}}是25(来自测试方法),但如果是Fiddler调用则为587)。
当我进行挖掘时,我发现我需要伪造SmtpClient,就像它可以正常工作一样(并且确实可以),并且我应该专注于该方法期望的其他事情,但是无法模拟SmtpClient。< / p>
Port
方法如下。
NotificationFactory
最后,public static class NotificationFactory
{
public static INotification GetNotification(NotificationType type)
{
switch (type)
{
case NotificationType.Mail: return new MailNotification();
default:
throw new Exception("Notification not registered on system");
}
}
public static INotification GetSmsNotification(SmsProviderType type)
{
switch (type)
{
//SMS codes
}
}
}
类如下。
MailNotification
提前谢谢!