Home > Back-end >  Nunit Moq: Unsupported expression: Value Non-overridable members may not be used in setup / verifica
Nunit Moq: Unsupported expression: Value Non-overridable members may not be used in setup / verifica

Time:05-31

I writing unit test for a function and for that I need to mock an entity. This is how I'm trying to mock:

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

RiskId is of type StringData : DataGeneric<string>. From the error, it appears that Moq dll is unable to fetch RiskId.Value because of the data type of RiskId.

Is there any way I can still mock RiskId.Value attribute as this is being used in the function for which I'm writing the test. Following is the error:

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

CodePudding user response:

Yes, you could implement your own implementation of ISimpleData like this:

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;

        // ...
    }
}

CodePudding user response:

I'm unaware of any built-in DataGeneric class, so I assume it is a user-defined class.

The error says

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

which means you should not mock the RiskId.Value.

You should try to setup a mock for the RiskId itself:

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

I've assumed your StringData has a constructor which can receive its value.

  • Related