Unit Testing Secure Controller Actions with Moq

added by mceranski
8/16/2010 8:27:59 AM

0 Kicks, 109 Views

One of the hardest things to unit test in MVC is security. Security is tough to test because there is a lot of setup involved in mocking the HttpContext, the Principal and the Identity. For example, in WeBlog I am using the following code in the Edit Post action. Post post = Repository.FirstOrDefault<Post>(x => x.ID == id); if (post == null) return View("NotFound"); if (!HttpContext.User.CanEditPost(post)) return View("PermissionDenied"); In order to make sure this code works properly I need to test it with an authorized and unauthorized user. Unfortunately, the HttpContext.User will not automatically be created for your tests so you have to mock one for each test that your perform. So lets start this journey by reviewing the code required to mock the HttpContext using the popular opensource library Moq. This code is a combination of code I discovered on Stackoverflow and Scott Hanselman’s MvcMockHelpers...