我有类似的代码。
[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方法必须是虚拟的才能模拟它,因为此代码中没有接口。
为了使测试用例运行,如果我将方法更改为虚拟,我想知道在实际应用程序运行时是否存在任何问题或不利之处?
答案 0 :(得分:0)
没问题。只有这样,您才能为其他编码人员打开改变课堂行为的大门(通常,您是最大的敌人,必须对自己有所保护;)
您违反了=>的建议,已关闭,无法进行扩展修改(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);