【发布时间】:2015-01-21 13:32:19
【问题描述】:
我是 C# 的 MOQ 新手。 这是我的代码:
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());
}
}
}
更新 我想通了:
- 我需要一个公钥
- 我需要将方法设为内部受保护虚拟
【问题讨论】:
标签: c#