ASP. net mvc 4 Practice Study Note 5: controller (lower ),
Iii. Unit Test-make sure the Controller executes as desired:
Unit testing is a small script-based test, which is usually written in the same language as the product code. They establish and practice the functions of a single component in the form of isolation from the rest of the system to verify that it works correctly.
1. Provided test items:
If you select the "Create Unit test project" option when creating a project, Visual Studio generates a test project with Visual Studio Unit Testing Framework (Visual Studio Unit test Framework), including the HomeControllerTest class:
1 namespace Guestbook. tests. controllers 2 {3 [TestClass] 4 public class HomeControllerTest 5 {6 [TestMethod] 7 public void Index () 8 {9 // Arrange10 HomeController controller = new HomeController (); // instantiate controller 11 12 // Act13 ViewResult result = controller. index () as ViewResult; // rehearsal Action Method 14 15 // Assert16 Assert. isNotNull (result); // asserted result 17} 18 19 [TestMethod] 20 public void About () 21 {22 // Arrange23 HomeController controller = new HomeController (); 24 25 // Act26 ViewResult result = controller. about () as ViewResult; 27 28 // Assert29 Assert. areEqual ("Your application description page. ", result. viewBag. message); 30} 31 32 [TestMethod] 33 public void Contact () 34 {35 // Arrange36 HomeController = new HomeController (); 37 38 // Act39 ViewResult result = controller. contact () as ViewResult; 40 41 // Assert42 Assert. isNotNull (result); 43} 44}
Each test has three phases: Arrange (preparation), Act (Action), and Assert ). This mode of writing and testing is usually referred to as the "A/A" mode or the "3A" mode. Unit testing adopts this fixed A/A programming mode, which is conducive to compiling A uniform test format.
2. Test GuestbookController:
In the previous Code, GuestbookController directly instantiates and uses the GuestbookContext object to access the database. This means that the controller cannot be tested if no database is created or there is no test data in the database.
Instead of directly accessing GuestbookContext, we introduce a repository to provide a gateway for performing data access operations on the GuestbookEntry object:
1. New interface:
1 namespace Guestbook.Repository 2 { 3 public interface IGuestbookRepository 4 { 5 IList<GuestbookEntry> GetMostRecentEntries(); 6 GuestbookEntry FindById(int? id); 7 IList<CommentSummary> GetCommentSummary(); 8 void AddEntry(GuestbookEntry entry); 9 void Edit(GuestbookEntry entry);10 void DeleteById(int id);11 }12 }
2. Implementation interface:
1 namespace Guestbook. repository 2 {3 public class GuestbookRepository: IGuestbookRepository 4 {5 private GuestbookContext _ db = new GuestbookContext (); 6 public IList <GuestbookEntry> GetMostRecentEntries () 7 {8 return (from entry in _ db. entries 9 orderby entry. dateAdded descending10 select entry ). take (20 ). toList (); 11} 12 public void AddEntry (GuestbookEntry entry) 13 {14 _ db. entries. add (entry); 1 5 _ db. SaveChanges (); 16} 17 public GuestbookEntry FindById (int? Id) 18 {19 var entry = _ db. entries. find (id); 20 return entry; 21} 22 public IList <CommentSummary> GetCommentSummary () 23 {24 var entries = from entry in _ db. entries25 group entry by entry. name into groupedByName26 orderby groupedByName. count () descending27 select new CommentSummary 28 {29 NumberOfComments = groupedByName. count (), 30 UserName = groupedByName. key31}; 32 return entries. toList (); 33 34} 35 public void Edit (GuestbookEntry entry) 36 {37 _ db. entry (entry ). state = EntityState. modified; 38 _ db. saveChanges (); 39} 40 public void DeleteById (int id) 41 {42 var entry = _ db. entries. find (id); 43 _ db. entries. remove (entry); 44 _ db. saveChanges (); 45} 46} 47}View Code
3. Modify GuestbookController:
1 namespace Guestbook. controllers 2 {3 public class GuestbookController: Controller 4 {5 private IGuestbookRepository _ repository; 6 7 public GuestbookController () 8 {9 _ repository = new GuestbookRepository (); 10} 11 12 public GuestbookController (IGuestbookRepository repository) 13 {14 _ repository = repository; 15} 16 public ActionResult Index () 17 {18 var mostRecentEntries = _ repository. getM OstRecentEntries (); 19 return View (mostRecentEntries); 20} 21 public ActionResult Details (int? Id) 22 {23 if (id = null) 24 {25 return new HttpStatusCodeResult (HttpStatusCode. badRequest); 26} 27 var entry = _ repository. findById (id); 28 if (entry = null) 29 {30 return HttpNotFound (); 31} 32 return View (entry); 33} 34 public ActionResult Create () 35 {36 return View (); 37} 38 [HttpPost] 39 [ValidateAntiForgeryToken] 40 public ActionResult Create ([Bind (Include = "Id, Name, Message, DateAdd Ed ")] GuestbookEntry entry) 41 {42 if (ModelState. isValid) // check whether the verification is successful 43 {44 _ repository. addEntry (entry); 45 return RedirectToAction ("Index"); 46} 47 48 return View (entry); // re-render Form 49} 50 public ActionResult Edit (int? Id) 51 {52 if (id = null) 53 {54 return new HttpStatusCodeResult (HttpStatusCode. badRequest); 55} 56 var entry = _ repository. findById (id); 57 if (entry = null) 58 {59 return HttpNotFound (); 60} 61 return View (entry ); 62} 63 [HttpPost] 64 [ValidateAntiForgeryToken] 65 public ActionResult Edit ([Bind (Include = "Id, Name, Message, DateAdded")] GuestbookEntry entry) 66 {67 if (ModelState. isValid) 68 {69 _ repository. Edit (entry); 70 return RedirectToAction ("Index"); 71} 72 return View (entry); 73} 74 public ActionResult Delete (int? Id) 75 {76 if (id = null) 77 {78 return new HttpStatusCodeResult (HttpStatusCode. badRequest); 79} 80 var entry = _ repository. findById (id); 81 if (entry = null) 82 {83 return HttpNotFound (); 84} 85 return View (entry); 86} 87 [HttpPost, actionName ("Delete")] 88 [ValidateAntiForgeryToken] 89 public ActionResult DeleteConfirmed (int id) 90 {91 _ repository. deleteById (id); 92 return RedirectToAction ("Index"); 93} 94 95 public ActionResult CommentSumary () 96 {97 var entries = _ repository. getCommentSummary (); 98 return View (entries. toList (); 99} 100} 101}View Code
4. Imitation Of The IGuestbookRepository interface that does not interact with the database:
1 namespace Guestbook. repository 2 {3 public class libraries: IGuestbookRepository 4 {5 public List <GuestbookEntry> _ entries = new List <GuestbookEntry> (); 6 public IList <GuestbookEntry> GetMostRecentEntries () 7 {8 return new List <GuestbookEntry> 9 {10 new GuestbookEntry11 {12 DateAdded = new DateTime (, 13), 13 Id = Message = "Test Message ", 15 Name = "Chen Jialuo" 16} 17}; 18} 19 public voi D AddEntry (GuestbookEntry entry) 20 {21 _ entries. Add (entry); 22} 23 public GuestbookEntry FindById (int? Id) 24 {25 return _ entries. singleOrDefault (x => x. id = id); 26} 27 public IList <CommentSummary> GetCommentSummary () 28 {29 return new List <CommentSummary> 30 {31 new CommentSummary32 {33 UserName = "Chen Jialuo ", 34 NumberOfComments = 335} 36}; 37 38} 39 public void Edit (GuestbookEntry entry) 40 {41 // 42} 43 public void DeleteById (int id) 44 {45 // 46} 47} 48}View Code
5. Test the Index action:
1 namespace Guestbook.Tests.Controllers 2 { 3 [TestClass] 4 public class GuestbookControllerTest 5 { 6 [TestMethod] 7 public void Index_RendersView() 8 { 9 var controller = new GuestbookController(new FakeGuestbookRepository());10 var result=controller.Index() as ViewResult;11 Assert.IsNotNull(result);12 }13 [TestMethod]14 public void Index_gets_most_rencent_entries()15 {16 var controller = new GuestbookController(new FakeGuestbookRepository());17 var result=(ViewResult)controller.Index();18 var entries=(IList<GuestbookEntry>) result.Model;19 Assert.AreEqual(1,entries.Count);20 }21 22 }23 }
The first test calls the Index action and simply asserted that it renders a view. The second asserted is passed to the view as a GuestbookEntry Object List.
Source code download password: bwmq