Mock Testing Using Visual Studio 2012

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).

  • Open Visual Studio 2012.create console project.

  • Select "File" -> "New" -> "Project..." then select "Windows" > "Console application" then give the name "MockTestingDemo".

    Image1.jpg

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:

  • EmployeeWebserviceClient: it will make a call to the employee Web service and get the employee data.
  • EmployeeMockTesting: it is the test projects where we will write your unit testing.

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

  • Write the following codes inside the interface.

    3.png

  • Add another class Employee.cs the same project. And write the following code inside that.


    4.png
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.

  • Right-click on the EmployeeWebserviceClient under reference and select "Add Fake Assembly".

    7.png

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.


Similar Articles