Test Driven Development in MVC

Hey Folks,


It is quite interesting to note how TDD make the Design simple when building software applications. In TDD the Developer first writes test cases which are then tested using Visual Studio Testing tools ,so as to define a desired improvement in the application .


Since I am currently working on MVC ,let me brief me how TDD can be made used while working for the same. Consider we have a Controller class in our app ,say ProductsController. Now  in my controller I have several ActionMethods . For eg lets consider a Create() Action Method as follows


public ActionResult Create()

{    
    ViewBag.Message = "Test";

    return View("Create");

}



As one can see ,This ActionMethod returns me a View named “Create” . Now I want to test this action and so as to display the correct View .


Step 1. When we create a new application, always check Create a Unit Test Project . The test framework   can be of your choice .In my case I have used Visual Studio Unit Test. We have other Nuget Framework like Nunit,xunit which can also be used for testing .
NOTE: I have changed the project name to WebAppTemplate.UI.Web for later




 Step 2. By default under Controllers folder there will already be a HomeControllerTest.cs file . We can also add one for our ProductsController by just right clicking on the Controllers folder àAddàUnit TestàBasic Unit Test which will have two attributes .One for the class and one for the Method 


[TestClass]

[TestMethod]






Step 3. Start writing the code



using Microsoft.VisualStudio.TestTools.UnitTesting;



[TestMethod]
//Testing if correct view returned or not


public void TestCreateView()

{  

     ProductsController controller = new ProductsController();

     ViewResult result = controller.Create() as ViewResult;

     Assert.AreEqual("Edit", result.ViewName);  

}

and than run the test by clicking on "Run Test in Current Context as shown by the red circle "



Step 4. Now this particular test will definitely fail since we are passing “Edit” as the Viewname which doesn’t match the actual view called Create.







No comments:

Post a Comment