Is it possible to set a property without setter using Moq?

I am doing some research. I want to use moq and pass it to the MVC to allow it to set some values ​​in the session. I wrote code to find out if it is possible to "open" a property without a setter. I just don’t know if this is possible ...

The following code was my attempt to set the witn no setter property!

using System; using System.Collections.Generic; using System.Linq; using System.Text; using Moq; namespace TestMoq { class Program { static void Main(string[] args) { var mock = new Mock<TestClass>(); mock.SetupProperty(f => f.VarWithNoSetter); mock.Object.VarWithNoSetter = "Set"; Console.WriteLine(mock.Object.VarWithNoSetter); Console.ReadLine(); } } public class TestClass { private string _varWithNoSetter; public string VarWithNoSetter { get { return _varWithNoSetter; } } public TestClass() { } } } 
+4
source share
3 answers

Of course:

 mock.SetupGet(f => f.VarWithNoSetter).Returns("Hi, Exitos!"); 
+7
source

Yes you can, but you have to make this property virtual, it’s possible, since Moq will generate proxies

 public virtual string VarWithNoSetter { get { return _varWithNoSetter; } } 

or you can use .SetUpGet

+1
source

For me, this does not work with SetUpGet without making the property virtual. However, it works with Mock.Of <>:

 var mock = Mock.Of<TestClass>(m=>m.VarWithNoSetter == "the value"); 
0
source

Source: https://habr.com/ru/post/1402262/


All Articles