将方法更改为虚拟以模拟方法的缺点

Downsides of changing the method to virtual to mock the method

我有类似的代码。

[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 bool SendEmail()
    {
        throw  new Exception("send email failed cuz bla bla bla");
    }
}

EmailService.SendEmail 方法必须是虚拟的才能模拟它,因为此代码中没有接口。

为了做测试用例运行,如果我把方法改成virtual,我想知道这样做有什么问题或缺点,当实际应用运行小号?

没问题。只有这样,您才能为其他编码人员修改您的 class 的行为打开大门(通常您是您最大的敌人,您必须保护自己免受伤害;)

您违反了 => 关闭修改开放扩展 (SOLID) 的建议。 还要记住,如果你必须做这样的事情是因为你依赖于具体的实现而不是抽象

public interface IEmailService
{            
    bool SendEmail();
}

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

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


//unit test => no need to make virtual anything
var mock = new Mock<IEmailService>();
mock.Setup(x => x.SendEmail()).Returns(true);