What is it ?

Mock testing is a type of unit testing for testing business logic that has some external dependency.

Audience of this blog: All who want to start mocking using Visual Studio 2012.

Why it is needed

Today's enterprise applications are doing at least one of following things:

  1. Getting data/storing data into database.
  2. Getting data/sending data to some external web services.

In both of the cases the user must depend on some external entities. Suppose a database or web service is not available at the time of development due to some factor. At this point the developer could mock the database/web service calls and test his business logic using mock unit testing.

1. Create your projects (here I am taking a console app that is fetching employee data from a web service).

On clicking "Ok" it will create a project with a default file Program.cs.

2. Add another file to the project called EmployeeBusinessManager.

3. Add one class library project and one unit test project to the solution. After adding them, the solution will look as in the following image.

2.png

Project Details:

4. Rename the Class1.cs file to EmployeeWebserviceProxy.cs and add an interface IEmployeeWebserviceClient to the project.

5. EmployeeWebserviceClient from the MockTestingDemo project. After adding the reference just write the following query inside the class EmployeeBusinessManager.

5.png

6. Now add a reference to the projects EmployeeWebserviceClient and MockTestingDemo from the unit test project.

6.png



7. Here we need to make a fake of the EmployeeWebserviceClient since the web service is not available, but we need to test our business logic inside the EmployeeBusinessManager class.

8. After selecting the option you will see the following folders and flies inside the unit test project.

8.png

9. Now update the UnitTEst1.cs file to EmployeeBusinessManagerTest.cs and write following code.

9.png

If you debug the test you will find the stub code will execute instead of the actual EmployeeWebserviceProxy's GetEmployee method.