Fakes Tutorial 2: Basic Stub Sample

This is in continuation to “Introduction to Microsoft Fakes

To Begin with Basic example of Stub, We have 3 Projects:

  1. BasicStub : This is simple class library with one method which is to be tested with Fakes Unit Testing
  2. ToBeStubbed : Contains code for an assembly which is referred in BasicStub Project and will be faked in unit test.
  3. BasicStubUnitTest: Unit test


Looking into Projects:

  1. ToBeStubbed

    This project Contains One Interface “IFetchRowCount” which is referred in Class “FetchRowCount”. This class will ideally contain logic which we need to fake




Here class FetchRowCount will be used in BasicStub class and method FetchNumberOfRows will be called.


  1. BasicStub


    In BasicStub Class we have method “MethodToTest” which we are interested in testing. Here important part is that we are passing object “fetch” to method.

    If it’s not implemented like this it will be difficult to test it using stubs (Discussion on how to handle other scenarios are for other postsJ)



  2. BasicStubUnitTest:


    First thing to be done in Unit test is to add reference to all the assemblies we need, Here it will be “BasicStub” for testing and “ToBeStubbed” for Faking.


    After that we’ll need to fake assembly TooBeStubbed for that

            Goto ToBeStubbed project, -> References -> Right Click assembly to be faked. -> Click Add Fakes Assembly


    Test Method:

    Below you can see that in test we have Created the object of Stub class StubIFetchCount generated from interface, Set the return value of method and then passed it to the method to be tested.

    Finally we have asserted it with our value “Average”.


    Above is the most basic unit test from fakes which can be done using “stub”. It doesn’t cover much detail but gives overview of how stub works.

    Keep reading for more posts around this.


    Next: “Basic Shim Sample

Leave a Reply

Your email address will not be published. Required fields are marked *