简体   繁体   English

如何存根具体 class 的 ReadOnly 属性

[英]How to Stub a ReadOnly property of a concrete class

Let's say I have a Concrete class with a Read-Only property eg假设我有一个具有只读属性的混凝土 class 例如

public class TestClass
{
   public bool Squid {get;private set;}
}

And now I want to stub the response to Squid eg现在我想存根对 Squid 的响应,例如

Squid squid = MockRepository.GenerateStub<Squid>();
squid.Stub(c => c.Squid).Return(true);

However when I run this I get the following error message: System.InvalidOperationException: Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).但是,当我运行它时,我收到以下错误消息: System.InvalidOperationException: Invalid call, last call has been used or no call has been made (确保您正在调用虚拟 (C#) / Overridable (VB) 方法) .

Is there any way of stubbing this property without creating an interface for the class?有没有办法在不为 class 创建接口的情况下对这个属性进行存根?

Yes, there is: Make the property virtual as already described in the exception message.是的,有:如异常消息中所述,使属性为virtual

You could use reflection to call the private setter.您可以使用反射来调用私有设置器。

Or use reflection to find the backing field and set it directly(A bit harder, but works on non auto-properties with a trivial getter).或者使用反射来查找支持字段并直接设置它(有点困难,但适用于具有微不足道的 getter 的非自动属性)。

And finally it's possible to use the profiling API for that.最后,可以为此使用分析 API。 (AFAIK Moles is based on that). (AFAIK Moles就是基于此)。

If any of that is a good idea is a different question...如果其中任何一个是一个好主意是一个不同的问题......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM