.net 什么开源模拟框架允许模拟SmtpClient
在手动测试了我以前的所有代码之后,我试图获得一些使用单元测试框架的经验。基于一些初步研究,我正在使用Microsoft测试和justMock Lite。但是,后来我遇到了一个相当简单的场景(从用户的角度来看),我无法处理这个场景,因为我只使用了开源版本限制。下面是用于发送邮件的场景 IEmailService接口.net 什么开源模拟框架允许模拟SmtpClient,.net,unit-testing,mocking,.net,Unit Testing,Mocking,在手动测试了我以前的所有代码之后,我试图获得一些使用单元测试框架的经验。基于一些初步研究,我正在使用Microsoft测试和justMock Lite。但是,后来我遇到了一个相当简单的场景(从用户的角度来看),我无法处理这个场景,因为我只使用了开源版本限制。下面是用于发送邮件的场景 IEmailService接口 public interface IEmailService { bool SendEmail(string recipient, string message, string
public interface IEmailService {
bool SendEmail(string recipient, string message, string from);
}
WebMailService实现
public class WebEmailService : IEmailService {
public bool SendEmail(string recipient, string message, string from) {
try {
MailMessage mail = new MailMessage(from, recipient,"",message);
SmtpClient client = new SmtpClient();
client.Send(mail);//This call needs to be mocked
return true;
}
catch (Exception) {
return false;
}
}
}
因此,我尝试使用JustMock Lite测试上述内容,如下所示
单元测试
[TestMethod]
public void SendMail_WhenNoExceptionThrown_ReturnsTrue() {
IEmailService mailService = new WebEmailService();
var smtpClient = Mock.Create<SmtpClient>();
Mock.Arrange(() => smtpClient.Send(Arg.IsAny<MailMessage>())).DoNothing().MustBeCalled();
bool returnCode = mailService.SendEmail("recipient", "message", "from");
Assert.AreEqual(true, returnCode);
}
[TestMethod]
public void SendMail_whennoexception抛出_ReturnsTrue()时{
IEmailService mailService=新的WebEmailService();
var smtpClient=Mock.Create();
Mock.Arrange(()=>smtpClient.Send(Arg.IsAny()).DoNothing().MustBeCalled();
bool returnCode=mailService.sendmail(“收件人”、“邮件”、“发件人”);
Assert.AreEqual(true,返回代码);
}
这导致了一个异常,我意识到这种模拟.Net方法在开源产品(JustMock Lite)中不受支持
那么,有没有一种方法可以使用开源模拟框架绕过这些场景,或者这是一个过分的问题
注意:我已经进入了一个包装器,并提取了相同的接口。但是,我只是想知道我们在不包装SmtpClient对象的情况下使用的其他方法。我建议如果工具有限制,不要使用它。除非你愿意付钱,否则就用I.eJustMock 你的情况很简单,我想你有两个选择 将SmtpClient方法包装在接口中并公开它们,以便 A.使用穷人模拟/手写的手动模拟 即 ISmtpClientService.SendEmail(…) 创建可测试的SmtpClient服务,该服务实现ISmtpClientService。此服务的真正实现是围绕真正SmtpClient的包装器 或者尝试从真正的SmtpClient继承-不确定这是否可能,即如果不可能,您可以创建一个可测试的版本,而不必像上面那样包装在接口中 B.Just Mock可能能够存根这些虚拟方法。非常确定它们允许客户端像其他免费框架一样存根虚拟方法这可能对您有所帮助: