是否可以使用Moq设置没有setter的属性?

Exi*_*tos 5 c# moq

我做了一些研究.我想使用moq并将其传递给MVC控制器,以便允许它在会话中设置一些值.我写了一些代码,看看它是否有可能"打开"一个没有setter的属性.只是不知道它是否可能......

以下代码是我试图设置一个没有setter的属性的尝试!

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()
        {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Cra*_*ntz 9

当然:

mock.SetupGet(f => f.VarWithNoSetter).Returns("Hi, Exitos!");
Run Code Online (Sandbox Code Playgroud)


Mas*_*uso 1

是的,您可以,但您必须将该财产设为虚拟,因为 Moq 将生成代理

public virtual string VarWithNoSetter
{
   get { return _varWithNoSetter; }
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用.SetUpGet