hbmaam hbmaam - 1 year ago 144
C# Question

How to mock non virtual methods?

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);
public class Customer
public bool AddCustomer(EmailService emailService)
Debug.WriteLine("new customer added");
return true;
public class EmailService
public virtual bool SendEmail()
throw new Exception("send email failed cuz bla bla bla");

method must be virtual to mock it. Is there any way to mock non virtual methods?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download