Moq System.NotSupportedException

问题描述

我一次又一次地得到它

System.NotSupportedException: 'Unsupported expression: c => c.ProductMaxLenght
Non-overridable members (here: ConfigurationService.get_ProductMaxLenght) 
may not be used in setup / verification expressions.'

当我尝试调用这个

var configurationService = new Mock<ConfigurationService>();
configurationService.SetupGet(c => c.ProductMaxLenght).Returns(productMaxLength)

我在 Startup 中调用 Initialize 并从 Configuratiom 获取所有数据 配置服务:

public class ConfigurationService
    {
        private IConfiguration _configuration;
        private int? _productMaxLength;
        public int? ProductMaxLenght
        {
            get
            {
                if (!_productMaxLength.HasValue)
                {
                    throw new ArgumentNullException(nameof(_productMaxLength));
                }
                return _productMaxLength;
            }
        }

        public void Initialize(IConfiguration configuration)
        {
            _configuration = configuration ?? throw new ArgumentNullException(nameof(_configuration));
            _productMaxLength = _configuration.GetValue<int>("ProductsMaxLength");
        }
    }

解决方法

您必须使该属性可覆盖,因此将其设为 virtual

public virtual int? ProductMaxLenght  { get ...

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...