Nunit Moq:不支持的表达式:值不可覆盖的成员不得用于设置/验证表达式

Nunit Moq: Unsupported expression: Value Non-overridable members may not be used in setup / verification expressions

我正在为一个函数编写单元测试,为此我需要模拟一个实体。这就是我试图嘲笑的方式:

Mock<ISimpleData> data = new Mock<ISimpleData>();
data.Setup(i => i.RiskId.Value).Returns("123");//gets error here

RiskIdStringData : DataGeneric<string> 类型。从错误来看,由于 RiskId.

的数据类型,Moq dll 似乎无法获取 RiskId.Value

有什么方法我仍然可以模拟 RiskId.Value 属性,因为它正在我正在为其编写测试的函数中使用。以下是错误:

System.NotSupportedException: Unsupported expression: ... => ....Value Non-overridable members (here: DataGeneric.get_Value) may not be used in setup / verification expressions. at Moq.Guard.IsOverridable(MethodInfo method, Expression expression) in C:\projects\moq4\src\Moq\Guard.cs:line 99 at Moq.InvocationShape..ctor(LambdaExpression expression, MethodInfo method, IReadOnlyList'1 arguments, Boolean exactGenericTypeArguments, Boolean skipMatcherInitialization, Boolean allowNonOverridable) in C:\projects\moq4\src\Moq\InvocationShape.cs:line 84 at Moq.ExpressionExtensions.g__Split|5_0(Expression e, Expression& r, InvocationShape& p, Boolean assignment, Boolean allowNonOverridableLastProperty) in C:\projects\moq4\src\Moq\ExpressionExtensions.cs:line 324 at Moq.ExpressionExtensions.Split(LambdaExpression expression, Boolean allowNonOverridableLastProperty) in C:\projects\moq4\src\Moq\ExpressionExtensions.cs:line 149 at Moq.Mock.Setup(Mock mock, LambdaExpression expression, Condition condition) in C:\projects\moq4\src\Moq\Mock.cs:line 505 at Moq.Mock`1.Setup[TResult](Expression'1 expression) in C:\projects\moq4\src\Moq\Mock'1.cs:line 454 System.Exception {System.NotSupportedException

是的,您可以像这样实现自己的 ISimpleData 实现:

public class MyTests
{
    [Test]
    public void MyTest()
    {
        // Arrange
        var data = new SimpleDataMock("123");

        // Act
        // ...

        // Assert
        // ...
    }

    private class SimpleDataMock : ISimpleData
    {
        public SimpleDataMock(string riskValue) => this.RiskId.Value = riskValue;

        // ...
    }
}

我不知道有任何 built-in DataGeneric class,所以我假设它是 user-defined class.

错误说

... Value Non-overridable members (here: DataGeneric.get_Value) ...

这意味着你不应该嘲笑 RiskId.Value

您应该尝试为 RiskId 本身设置一个模拟:

data.Setup(i => i.RiskId).Returns(new StringData("123"));

我假设你的 StringData 有一个构造函数可以接收它的值。