MVC::CreatingUnitTestsforASP.
NETMVCApplications
Theg
oalofthistutorialistodemonstratehowyoucanwriteunittestsforthecontrollersinyourASP.NETMVCapplications.Wediscusshowtobuildthreedifferenttypesofunittests.Youlearnhowtotesttheviewreturnedbyacontrolleraction,howtotesttheViewDatareturnedbyacontrolleraction,andhowtotestwhetherornotonecontrolleractionredirectsyoutoasecondcontrolleraction.
CreatingtheControllerunderTest
Let’sstartbycreatingthecontrollerthatweintendtotest.Thecontroller,namedtheProductController,iscontainedinListing1.Listing1–ProductController.csusingSystem;usingSystem.Web.Mvc;
namespaceStore.Controllers{publicclassProductController:Controller{publicActionResultIndex(){//AddactionlogicherethrownewNotImplementedException();}
publicActionResultDetails(intId){returnView("Details");}
}}
TheProductControllercontainstwoactionmethodsnamedIndex()andDetails().Bothactionmethodsreturnaview.NoticethattheDetails()actionacceptsaparameternamedId.
TestingtheViewreturnedbyaController
ImaginethatwewanttotestwhetherornottheProductControllerreturnstherightview.WewanttomakesurethatwhentheProductController.Details()actionisinvoked,theDetailsviewisreturned.ThetestclassinListing2containsaunittestfortestingtheviewreturnedbytheProductController.Details()action.Listing2–ProductControllerTest.csusingSystem.Web.Mvc;usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingStore.Controllers;
namespaceStoreTests.Controllers{[TestClass]publicclassProductControllerTest{[TestMethod]publicvoidTestDetailsView(){varcontroller=newProductController();varresult=controller.Details(2)asViewResult;Assert.AreEqual("Details",result.ViewName);}}}TheclassinListing2includesatestmethodnamedTestDetailsView().Thismethodcontainsthreelinesofcode.ThefirstlineofcodecreatesanewinstanceoftheProductControllerclass.Thesecondlineofcodeinvokesthecontroller’sDetails()actionmethod.Finally,thelastlineofcodecheckswhetherornottheviewreturnedbytheDetails()actionistheDetailsview.TheViewResult.ViewNamepropertyrepresentsthenameoftheviewreturnedbyacontroller.Onebigwarningabouttestingthisproperty.Therearetwowaysthatacontrollercanreturnaview.Acontrollercanexplicitlyreturnaviewlikethis:publicActionResultDetails(intId){
returnView("Details");}
Alternatively,thenameoftheviewcanbeinferredfromthenameofthecontrolleractionlikethis:publicActionResultDetails(intId){returnView();}
ThiscontrolleractionalsoreturnsaviewnamedDetails.However,thenameoftheviewisinferredfromtheactionname.Ifyouwanttotesttheviewname,thenyoumustexplicitlyreturntheviewnamefromthecontrolleraction.YoucanruntheunittestinListing2byeitherenteringthekeyboardcombinationCtrl-R,AorbyclickingtheRunAllTestsinSolutionbutton(seeFigure1).Ifthetestpasses,you’llseetheTestResultswindowinFigure2.