As you know ASP.NET MVC fully supports Test Driven Development approach where you can write your test cases first and on the basis of output or result you can write your actual code for development. Any Software which has their Data Access Layer or Business Layer, they should be tested before going to production. If these layers are tested it means you are going in right direction.

You can write test cases for all Public Methods, which needs to be tested.
First you just need to create an ASP.NET MVC application. To create a new ASP.NET MVC application with Test Project, Open Visual Studio choose File, New, then Project.
It will open a New Project window, from where you need to choose node as Visual C# and then Web and from the right pane you need to choose ASP.NET Web Application. Name the application.

It will open a new window from where you can choose different type of the ASP.NET MVC project template. You need to choose MVC and also be sure you have checked on Add Unit tests and click OK.

It will add both projects for you. One is your actual project and another one is your test project. In the test project, you can write your actual test cases to test the action method. See the following image which will describe the actual structure of your solution.

Now open your HomeController.cs which is already created at the time of project creation with some default action method. You can see inside the HomeController.cs, there is a simple Index method, which return nothing but only a view.

Now you need to go inside your Test project and you will find a default created Controller “HomeControllerTest” with test cases which is already defined in Index action method.

There are some attributes and objects, used to create the test cases.
- TestClass: This attribute defines that this class is being used for test cases and this must be defined with Test Cases Class.
- TestMethod: It describes that the particular method which uses TestMethod attribute, is participating in Test Cases.





Sridhar YelagandhulaPosted Jan 14, 2020, 11:55 PM
Good Explanation...Nice!!!!!!
Rizwan KhanPosted Dec 30, 2017, 10:00 AM
Nice article, please provide your help to mock local variable or service object that used inside a method body. And these variables are completely local inside method no constructors are used. public int Add(int a) { int b=5; //want to mock this var TestService test = new TestService(); //want to mock this object int a = test.Add(b);// how to mock set up for this return a + a; }
Manoj KallaPosted Jan 21, 2016, 3:07 AM
Very nice article..
Humayun Kabir MamunPosted Dec 7, 2015, 3:15 AM
Nice...
Ankit BansalPosted Dec 7, 2015, 12:50 AM
nice one..thanks
Aishwarya DPosted Dec 7, 2015, 12:17 AM
Nice Article
Jaipal ReddyPosted Dec 6, 2015, 11:02 PM
Nice share.
Imran Javed ZiaPosted Dec 6, 2015, 4:58 PM
Nice article
Ravi PatelPosted Dec 6, 2015, 11:44 AM
nice explanation sir
Ankur MistryPosted Dec 6, 2015, 5:56 AM
good example