【问题标题】:What open source mocking framework will allow to mock SmtpClient什么开源模拟框架将允许模拟 SmtpClient
【发布时间】:2014-07-26 12:51:31
【问题描述】:

在手动测试了我以前的所有代码后,我试图获得一些使用单元测试框架的经验。根据一些初步研究,我正在使用 Microsoft Tests 和 justMock Lite。但是,后来我遇到了一个相当简单的场景(从用户的角度来看),由于仅使用开源版本限制,我无法处理。这是用于发送邮件的场景。

IEmailService接口

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);
}

这导致了一个异常,我意识到开源产品(JustMock Lite)不支持这种模拟.Net方法。

那么,有没有办法使用开源模拟框架来解决这种情况,或者问太多了。

注意:我已经通过option of wrapping the SmtpClient 进入包装器,并提取相同的接口。但是,我只是想知道我们在不包装 SmtpClient 对象的情况下工作的其他方法。

【问题讨论】:

标签: .net unit-testing mocking


【解决方案1】:

如果该工具有限制,我建议不要使用它。使用 I.eJustMock 除非您愿意为此付费

我认为你的场景很简单,所以你有几个选择

将您的 SmtpClient 方法包装在一个接口中并公开它们,以便您可以

A.使用穷人模拟/手写手动模拟。

即 ISmtpClientService.SendEmail(...)

您创建实现 ISmtpClientService 的可测试 SmtpClient 服务。该服务的真正实现是真正的 SmtpClient 的包装器

或者尝试从真正的 SmtpClient 继承 - 不确定这是可能的,如果不是,你可以创建一个可测试的版本,而不必像上面那样包装在一个接口中

B. Just Mock 可能能够存根这些虚拟方法。可以肯定的是,它们确实允许客户端像其他免费框架一样存根虚拟方法

【讨论】:

    猜你喜欢
    • 2011-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多