Microsoft Fakes Framework - Shim
I was writing the unit test cases using the Microsoft Fakes
framework so thought to share my knowledge with you all. I majorly used Shim to
write my test cases, so this post mostly focuses on Shim. I will write another
post on Stub in coming days.
As most of you know that this is not the only one framework
in market to write fake unit test cases the advantage of using this framework on
the other is that you have full control on the test case. It will allow you to
test your test case if some part of the application is not ready.
Why to use Shim?
The basic question will come in your mind that why to use
Shim not the Stub. For me both are same and depend on the design of your
application. If you are using any design pattern in your application except
singleton then it will be advisable to use the Stub because it work very well
with “Interfaces” and it is clearly mentioned in the Microsoft site as well.
Shim basically reduces the burden from the compiler by not
making the run time call to the specific methods, it run the Shim code. So, the
thumb rule is to use the stubs for the project within the visual studio IDE and
use the shim for external libraries where you do not have any control.
If you are on this line then I am hoping that now you have some
basic understand and use of Microsoft Fake framework. So let’s get started
Step 1. Create a new project in visual studio. For this post
I used the ASP.NET MVC
Step 2. Create a new method
Step 3. Build the project
Step 4. Add Test project
Step 5. Add Microsoft Quality Tools using below nuget
command
Install-Package Fakes.Contrib -Version
0.8.18200.2
Step 6. Add project library to test project and right click
on the library to add fake assembly.
Step 7. By doing the
step 6, it will add fake assembly to the project
Step 8. Finally, we are
ready to write the test case. Add a new class to test project and name it
whatever you want and don’t forgot the add namespaces (using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;)
and decorate the class with attribute ([TestClass]).
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject1
{
[TestClass]
public class TestClass
{
[TestMethod]
public void
StudentExist()
{
bool flgStatus = false;
WebApplication4.Controllers.Fakes.ShimHomeController.AllInstances.StudentExistStringString =
(a, b, c) =>
{
flgStatus = true;
return flgStatus;
};
WebApplication4.Controllers.HomeController objHome = new WebApplication4.Controllers.HomeController();
Assert.AreEqual(objHome.StudentExist("First", "Last"), flgStatus);
}
}
}
Step 9. Build the
solution
Step 10. The last piece of
work is to run the test case. Right click on the test case and select the run
test case. If build successful then in test explorer to you see your test successfully
executed.







Comments