开发者

Difference between SetupSet and SetupProperty in Moq

开发者 https://www.devze.com 2023-01-23 22:29 出处:网络
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 anyo开发者_运维技巧ne point me the actua

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 anyo开发者_运维技巧ne point me the actual difference between them?


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);


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消