I've put together a solution based on previous answers, the Microsoft documentation, and my own experimentation. I've also changed the TestMethod
a bit to show how I would actually use it for testing. Note: I haven't compiled this specific code, so I apologize if it doesn't work as is.
[TestClass]
class TestClass
{
[TestMethod]
public void TestMethod()
{
using (ShimsContext.Create())
{
Child child = CreateShimChild("foo", "bar");
Assert.AreEqual("foo", child.address); // Should be true
Assert.AreEqual("bar", child.Name); // Should be true
}
}
private ShimChild CreateShimChild(string foo, string bar)
{
// Create ShimChild and make the property "address" return foo
ShimChild child = new ShimChild() { addressGet = () => foo };
// Here's the trick: Create a ShimParent (giving it the child)
// and make the property "Name" return bar;
new ShimParent(child) { NameGet = () => bar };
return child;
}
}
I have no idea how the returned child knows that its Name
should return "bar", but it does! As you can see, you don't even need to save the ShimParent
anywhere; it's only created in order to specify the value for the Name
property.