class Parent{
public string Name{ get; set; }
}
class Child :Parent{
public string address{ get; set; }
}
[TestClass]
class TestClass{
[TestMethod]
public void TestMethod()
{
var c = new Fakes.Child();
c.addressGet = "foo"; // I can see that
c.NameGet = "bar"; // This DOES NOT exists
}
}
How can I set the "name" in the above code sample?
In computer programming, a shim is a small library which transparently intercepts an API, changes the parameters passed, handles the operation itself, or redirects the operation elsewhere. Shims can also be used for running programs on different software platforms than they were developed for.
Shim, in C#, is a template class that is derived from a base class with derived classes that inherit the data and behavior of the base class and vary only in the type. The derived class of the shim class reuses the implementation provided by the shim class.
Microsoft Fakes helps you isolate the code you're testing by replacing other parts of the application with stubs or shims. The stubs and shims are small pieces of code that are under the control of your tests.
The generated class for Parent
will have a constructor that looks like: ShimParent(Parent p)
.
All you need to do is:
var child = new ShimChild();
var parent = new ShimParent(child);
And set the appropriate values on the respective Shim's.
You'll have to declare it on the base class. The easiest way is to call the base class its AllInstances property:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
ClassLibrary1.Child myChild = new ClassLibrary1.Child();
using (ShimsContext.Create())
{
ClassLibrary1.Fakes.ShimChild.AllInstances.addressGet = (instance) => "foo";
ClassLibrary1.Fakes.ShimParent.AllInstances.NameGet = (instance) => "bar";
Assert.AreEqual("foo", myChild.address);
Assert.AreEqual("bar", myChild.Name);
}
}
}
Also always try to add the ShimsContext to ensure the proper cleaning of your shim. Otherwise your other unit tests will also get the values returned that you have declared before. Information on ShimsContext can be found here: http://msdn.microsoft.com/en-us/library/hh549176.aspx#ShimsContext
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With