小编典典

如何模拟非虚拟方法?

c#

[TestMethod]
public void TestMethod1()
{
    var mock = new Mock<EmailService>();
    mock.Setup(x => x.SendEmail()).Returns(true);
    var cus = new Customer();
    var result = cus.AddCustomer(mock.Object);
    Assert.IsTrue(result);
}

public class Customer
{
    public bool AddCustomer(EmailService emailService)
    {
        emailService.SendEmail();
        Debug.WriteLine("new customer added");
        return true;
    }
}

public class EmailService
{            
    public virtual bool SendEmail()
    {
        throw  new Exception("send email failed cuz bla bla bla");
    }
}

EmailService.SendEmail方法必须是虚拟的才能进行模拟。有什么方法可以模拟非虚拟方法?


阅读 291

收藏
2020-05-19

共1个答案

小编典典

Moq无法在类上模拟非虚拟方法。可以使用其他模拟框架,例如将模拟
IL实际编织到程序集中的Type模拟隔离器,或者在其上放置接口EmailService并对其进行模拟。

2020-05-19