繁体   English   中英

为什么MOQ框架会覆盖所有虚拟方法-C#

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM