【问题标题】:Converting Mock concrete object to interface resulting empty implementation将 Mock 具体对象转换为接口导致空实现
【发布时间】:2015-11-05 11:47:29
【问题描述】:

我使用 moq 进行单元测试已经有一段时间了, 我想知道为什么我的模拟对象即使它实现了接口方法也无法转换为接口在转换为接口后什么也不返回,这是我的简单代码:

POSRepository repo = this.mockPosRepository.Object;
IPOSRepository posRepo = repo;
if(repo.Prices.Count() > 0) // True
if(posRepo.Prices.Count() > 0) // false

我错过了什么吗?

【问题讨论】:

  • 如何创建this.mockPosRepository

标签: c# .net unit-testing mocking moq


【解决方案1】:

你可以使用As方法给mock对象添加接口,像这样:

mockPosRepository.As<IPOSRepository>();

不幸的是,如果类实现了接口,moq 不仅可以转换对象。

【讨论】:

    【解决方案2】:

    @domysee,感谢您的回复我已经通过检查创建过程设法解决了这个问题,我应该创建一个真实的类而不是模拟类...我创建了一个类似于此代码的问题

       [TestMethod]
        public void Test_Clean_Price()
        {
            Mock<CalcProcessor> calcProcessor = new Mock<CalcProcessor>();
            calcProcessor.Setup(s => s.AddProcessor(It.IsAny<int>(), It.IsAny<int>())).Returns(1);
            Mock<Calc> calc = new Mock<Calc>(calcProcessor.Object);//this should not a mock object
            ICalc icalc = calc.Object;
            int resultObject = calc.Object.Add(1, 2);
            int resultInterface = icalc.Add(1, 2);
    
            Assert.AreEqual(1,resultObject);//result 0
            Assert.AreEqual(1, resultInterface);//result 0
    
        }
    }
    public class CalcProcessor
    {
        public virtual int AddProcessor(int a, int b)
        {
            return a + b;
        }
    }
    
    public class Calc : ICalc
    {
        private CalcProcessor cp;
    
        public Calc(CalcProcessor calcp)
        {
            this.cp = calcp;
        }
        public virtual int Add(int a, int b)
        {
            return this.cp.AddProcessor(a,b);
        }
    
        public virtual int Substract(int a, int b)
        {
            throw new NotImplementedException();
        }
    }
    
    
    public interface ICalc
    {
        int Add(int a, int b);
    
        int Substract(int a, int b);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 2015-04-11
      相关资源
      最近更新 更多