[英]why MOQ framework overrides all virtual methods - c#
我是C#中的最小起訂量的新手。 這是我的代碼:
public class CustomerBase
{
private List<Customer> customers = new List<Customer>();
public const int MAX_CUSTOMERS = 100;
public int CustomerCount()
{
return customers.Count();
}
public void AddCustomer(string name, string email)
{
if (CustomerCount() >= MAX_CUSTOMERS)
{
return;
}
Customer cus = new Customer(name);
customers.Add(cus);
SendEmail(email);
}
public virtual void SendEmail(string email)
{
throw new NotImplementedException();
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestAddUser()
{
Mock<CustomerBase> m = new Mock<CustomerBase>();
m.Setup(x => x.SendEmail("k")).Verifiable(); // bypass send email because email is server is not setup
m.Object.AddCustomer("max", "k@g");
Assert.AreEqual(1, m.Object.CustomerCount());
}
}
測試通過。 一旦將CustomerCount虛擬化,測試將失敗,因為該方法開始返回零。 有誰知道為什么以及如何防止這種行為?
更新的代碼-使用內部程序集失敗:
[assembly: InternalsVisibleTo("UnitTestProject1")] // make the test assembly internal
namespace MoqSmple1
{
public class CustomerBase
{
private List<Customer> customers = new List<Customer>();
public const int MAX_CUSTOMERS = 100;
internal virtual int CustomerCount()
{
return customers.Count();
}
public void AddCustomer(string name, string email)
{
if (CustomerCount() >= MAX_CUSTOMERS)
{
return;
}
Customer cus = new Customer(name);
customers.Add(cus);
SendEmail(email);
}
internal virtual void SendEmail(string email)
{
throw new NotImplementedException();
}
}
}
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestAddUser()
{
Mock<CustomerBase> m = new Mock<CustomerBase>();
m.Setup(x => x.SendEmail("k")).Verifiable(); // bypass send email because email is server is not setup
m.Object.AddCustomer("max", "k@g");
m.CallBase = true;// keep the default behaviour of virtual methods except the ones skipped
Assert.AreEqual(1, m.Object.CustomerCount());
}
}
}
我發現的更新 :
您想要設置<YourMock>.CallBase = true
。 這是關於CallBase
的好文章
簡而言之,Moq將默認為所有虛擬方法創建代理,並且將CallBase設置為true會保留默認實現,除非您明確要求代理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.