Setting the mock property through Setup calls "Expression is not a method call"

I have the code below where my Mock interface has a Recorder property, which is a class.

Then I try to set a property in this class, but I get an error Expression is not a method invocation. Could you help me?

A runtime error when it tries to set the enum property. It throws an ArgumentException using the following stack trace:

at Moq.ExpressionExtensions.ToMethodCall(LambdaExpression expression)
   at Moq.Mock.<>c__DisplayClass1c`2.<Setup>b__1b()
   at Moq.PexProtector.Invoke[T](Func`1 function)
   at Moq.Mock.Setup[T,TResult](Mock mock, Expression`1 expression, Func`1 condition)
   at Moq.Mock`1.Setup[TResult](Expression`1 expression)

thank

//Works
var mock = new Moq.Mock<IEngine>(); 
//Works
mock.Setup(x => x.Recorder).Returns(new Moq.Mock<Recorder>().Object);  
//Fails on the next line assigning a property value!!!
mock.Setup(x => x.Recorder.RunState).Returns(Recorder.eRunStates.Play);  

UPDATE - I found that RunState is not a property, but a field / member, which is an enumeration

+5
source share
4 answers

, Recorder, , , . , -.

var mockRecorder = new Moq.Mock<Recorder>();
mockRecorder.Object.RunState = Recorder.eRunStates.Play;
+7

, , :

var mockRecorder = new Moq.Mock<Recorder>();
mock.Setup(x => x.Recorder).Returns(mockRecorder.Object);
mockRecorder.Setup(x => x.RunState).Returns(Recorder.eRunStates.Play);

, Moq - .

, , . , - , .

: , :

// Moq will set up the hierarchy for you...
mock.Setup(x => x.Recorder.RunState).Returns(Recorder.eRunStates.Play);
+4

SetupGet , ,

var mockRecorder = new Moq.Mock<Recorder>();
mock.SetupGet(x => x.Recorder).Returns(mockRecorder.Object);
mockRecorder.SetupGet(x => x.RunState).Returns(Recorder.eRunStates.Play);
+2

Mock RunState.

var mockRecorder = new Mock<Recorder>();
mockRecorder.Setup(x => x.RunState).Returns(eRunStates.Play);

mock.Setup(x => x.Recorder).Returns(mockRecorder.Object);

EDIT: FYI, you need to make all the settings for the layout before accessing the .Object property, since the object was created at that moment, and further settings cannot happen.

In addition, with a few suggestions, it looks like your enum for startup states is nested in your recorder class, I moved it to a separate class and further remove the 'e' prefix.

+1
source

All Articles