Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between SetupSet and SetupProperty in Moq

I understand that SetupSet is old way of setting up property in Moq. It's obsolette now but my intellisense shows both with none of them marked Obsolette. Can anyone point me the actual difference between them?

like image 637
DotNetInfo Avatar asked Nov 09 '10 02:11

DotNetInfo


2 Answers

I probably found one of the difference as follows.

If you are trying to mock a Readonly property, you have to use SetupGet as SetupProperty doesn't work in that case. Whereas SetupProperty can be used for non readonly properties if you want to set expectation.

For example, below won't work

public interface IXyz
{
  int Id { get; }
}

//Test Side Code    
var _mock = new Mock<IXyz>();
_mock.SetupProperty(x => x.Id, 1054);

If you try executing above code, it will come up saying System.ArgumentException: Property IXyz.Id is read-only

So if you change the code to below, it will work

_mock.SetupGet(x => x.Id).Returns(1054);
like image 99
DotNetInfo Avatar answered Oct 18 '22 01:10

DotNetInfo


SetupSet is not marked obsolete. You might be thinking of ExpectSet, which is marked as obsolete with the message, "ExpectSet has been renamed to SetupSet."

SetupSet lets you indicate an expectation that the property will be set:

mock.SetupSet(x => x.Prop = "bar").Verifiable();
mock.Object.Prop = "foo";
mock.Verify();   // fails

SetupProperty looks like a way to stub a property on the mock (see the same section of the documentation as for SetupSet).

like image 15
Jeff Ogata Avatar answered Oct 18 '22 01:10

Jeff Ogata