Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get shims for base classes using Microsoft Fakes?

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?

like image 749
kalrashi Avatar asked Feb 16 '13 23:02

kalrashi


People also ask

What is Microsoft shims?

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.

What is shims in c#?

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.

How does Microsoft fake work?

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.


2 Answers

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.

like image 120
Jesus is Lord Avatar answered Sep 24 '22 00:09

Jesus is Lord


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

like image 31
smeel Avatar answered Sep 20 '22 00:09

smeel