[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方法必须是虚拟的才能进行模拟。有什么方法可以模拟非虚拟方法?
EmailService.SendEmail
Moq无法在类上模拟非虚拟方法。可以使用其他模拟框架,例如将模拟 IL实际编织到程序集中的Type模拟隔离器,或者在其上放置接口EmailService并对其进行模拟。
EmailService