本文介绍了如何模拟非虚方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
[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
方法必须是虚拟嘲笑它。有没有什么办法来模拟非虚方法?
The EmailService.SendEmail
method must be virtual to mock it. Is there any way to mock non virtual methods?
推荐答案
起订量不能嘲笑的类非虚方法。或者使用其他嘲讽的框架,比如型模拟隔离这实际上编织IL到您的装配或放在 EmailService 和嘲笑的。
Moq cannot mock non virtual methods on classes. Either use other mocking frameworks such as Type mock Isolator which actually weaves IL into your assembly or place an interface on EmailService
and mock that.
这篇关于如何模拟非虚方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!