I am writing some unit tests for an extension method I have written on IPrincipal
. To assist, I have created a couple of helper classes (some code for not-implemented members of the interfaces has been omitted for brevity):
public class IPrincipalStub : IPrincipal
{
private IIdentity identityStub = new IIdentityStub();
public IIdentity Identity
{
get { return identityStub; }
set { identityStub = value; }
}
}
public class IIdentityStub : IIdentity
{
public string Name { get; set; } // BZZZT!!!
}
However, the Name
property in the IIdentity
interface is read-only (the IIDentity
interface specifies a getter but not a setter for the Name property).
How can I set the Name property in my stub object for testing purposes if the interface has defined it as a read-only property?
I recommend using a Mock library like NMock
You're using the auto-properties feature of C# but instead you should go the manual route and create a backing field for the property. Once you have a backing field you can set its value in the constructor (or make it a public field and set it after you have the object, but this is a little uglier).
I agree with juharr - use a mocking/isolation framework. I'd recommend Moq.
The following will print "Robert":
EDIT: But if you want to do it by hand...
(The above is not a unit test, just an example of hand-rolled stubs using a bit of dependency injection.)