Moq没有调用抽象方法

时间:2018-12-14 12:54:21

标签: c# moq abstract-class abstract factory-pattern

我的应用程序中有一些使用抽象工厂模式的代码:具有抽象依赖项的抽象类。具体的依赖关系应由抽象类的构造函数中的具体类权利来传递。但是,当我要模拟具体的类时,Moq从未调用具体的实现。代码如下:

using Moq;
using Xunit;

namespace Example
{
    public abstract class AbstractClass
    {
        public AbstractDependency Dependency { get; private set; }

        protected AbstractClass()
        {
            // This constructor is called by Moq
            Dependency = CreateDependency();    
        }

        protected abstract AbstractDependency CreateDependency();
    }

    public class ConcreteClass : AbstractClass
    {
        // Problem: This method is not called by Moq
        protected override AbstractDependency CreateDependency()
        {
            return new ConcreteDependency();
        }
    }

    public abstract class AbstractDependency
    {
    }

    public class ConcreteDependency : AbstractDependency
    {
    }

    public class Tests
    {
        [Fact]
        public void Test1()
        {
            // The following passes. The concrete implementation of CreateDependency is called!
            ConcreteClass concreteClass = new ConcreteClass();
            Assert.NotNull(concreteClass.Dependency);

            // The following fails. When code is run with the mock the concrete implementation of CreateDependency is not called!
            Mock<ConcreteClass> concreteClassMock = new Mock<ConcreteClass>();
            Assert.NotNull(concreteClassMock.Object.Dependency);
        }
    }
}

那是为什么?我认为Moq应该能够解决具体的类并实例化它。以及如何在不更改生产代码的情况下进行修复?

0 个答案:

没有答案