Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Stub a ReadOnly property of a concrete class

Let's say I have a Concrete class with a Read-Only property e.g.

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

And now I want to stub the response to Squid e.g.

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

Is there any way of stubbing this property without creating an interface for the class?

like image 418
Mark 909 Avatar asked Jan 19 '23 05:01

Mark 909


2 Answers

Yes, there is: Make the property virtual as already described in the exception message.

like image 105
Daniel Hilgarth Avatar answered Jan 26 '23 00:01

Daniel Hilgarth


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

And finally it's possible to use the profiling API for that. (AFAIK Moles is based on that).

If any of that is a good idea is a different question...

like image 21
CodesInChaos Avatar answered Jan 25 '23 23:01

CodesInChaos