ASP. net mvc Tip #12-copying controller Context

Source: Internet
Author: User
ASP. net mvc Tip #12-copying controller Context

Address: http://weblogs.asp.net/stephenwalther/archive/2008/06/30/asp-net-mvc-tip-12-faking-the-controller-context.aspx

Translation: Anders Liu

Abstract: In this Tip, Stephen Walther describes how to conduct a test in ASP. NET when creating a unit test for an ASP. net mvc application. Stephen Walther describes how to create a set of standard imitation objects (Fake Object) to mimic the current user, current user role, request parameters, session status, and Cookie.

ASP. net mvc applications are more testable than ASP. NET Web Forms applications. Every feature of ASP. net mvc has been designed with attention to testability. However, there are still some aspects in the ASP. net mvc application that are hard to be tested. In particular, testing ASP. NET in ASP. net mvc is still a challenge.

What does "ASP. NET" mean? It refers to the things that appear in HttpContext. These objects:

  • Request. Forms -- POST form parameters to a page.
  • Request. QueryString -- the query string parameter passed to a page.
  • User -- the current User who initiates the page request.
  • Reqest. Cookies -- the browser Cookie passed to the page.
  • Session: the Session state object.

For example, if you want to test a specific controller, which is actually a specific session Status entry, you need to create a unit test similar to the following:

<Br/> [TestMethod] <br/> public void TestSessionState () <br/>{< br/> // Arrange <br/> var controller = new HomeController (); <br/> // Act <br/> var result = controller. testSession () as ViewResult; <br/> // Assert <br/> Assert. areEqual ("wow! ", Controller. HttpContext. Session [" item1 "]); <br/>}< br/>

This test checks whether the Controller operation named TestSession () adds a new entry named item1 to the session status and whether the value is "wow! ".

The following controller operations can pass this test:

<Br/> public ViewResult TestSession () <br/> {<br/> Session ["item1"] = "wow! "; <Br/> return View (); <br/>}< br/>

This control operation inserts an expected entry into the session state.

Unfortunately, if you run this unit test, the test will fail. The cause of the failure is that an NullReferenceException occurs. The problem here is that the session status does not exist in the context of unit test. In fact, in a test method, anything inside ASP. NET does not exist. This means that you cannot test Cookies, form parameters, query string parameters, and user entities or user roles.

Mocking VS Stubbing

If you need to write a unit test for the user's internal ASP. NET object, you must make a choice. You have two options: Mock Ojbect Framework or Fake Class ).

The first option is to forge an internal ASP. NET object, which can be completed using mock Ojbect Framework such as Moq, Typemock Isolator, or Rhino Mocks. Any of these frameworks can generate objects that pretend to be internal ASP. NET objects. If you want to learn more about these frameworks, refer to my previous blog on these three Mock Ojbect frameworks:

  • Http://weblogs.asp.net/stephenwalther/archive/2008/06/11/tdd-introduction-to-moq.aspx
  • Http://weblogs.asp.net/stephenwalther/archive/2008/03/22/tdd-introduction-to-rhino-mocks.aspx
  • Http://weblogs.asp.net/stephenwalther/archive/2008/03/16/tdd-introduction-to-typemock-isolator.aspx

Another option is to create a group of classes to simulate internal ASP. NET objects. This set of classes can be created only once and then used in all future ASP. net mvc projects.

In this Tip, I will introduce the second method. I will show you how to simply test ASP. NET internal objects by creating a set of standard ASP. NET internal Object imitation classes without using Mock Object Framework.

Create a replica controller Context

At the end of the Tip, you can download these imitation classes. I created a group of ASP. NET internal object imitation classes named respectively:

  • FakeControllerContext
  • FakeHttpContext
  • FakeHttpRequest
  • FakeHttpSessionState
  • FakeIdentity
  • FakePrincipal

Create an instance of FakeControllerContext in the unit test and assign it to the ControllerContext attribute of the Controller to start using these imitation classes. For example, the following shows how to use the FakeControllerContext class to duplicate a specific user in a unit test.

<Br/> var controller = new HomeController (); <br/> controller. ControllerContext = new FakeControllerContext (controller, "Stephen"); <br/>

After FakeControllerContext is assigned to the Controller, the Controller will use this context for the rest of the unit test. Let's use different examples to see how to use FakeControllerContext to simulate different ASP. NET internal objects.

Test form parameters

Suppose you want to pass different form parameters to the operation to test the behavior of the controller operation. In addition, assume that the controller directly accesses Reques. Form as follows:

<Br/> public ActionResult Insert () <br/> {<br/> ViewData ["firstname"] = Request. form ["firstName"]; <br/> ViewData ["lastName"] = Request. form ["lastName"]; <br/> return View (); <br/>}< br/>

How can I test the Controller operation? In this case, you can use the FakeControllerContext constructor that accepts a set of form parameters. The following test checks whether the firstName and lastName form parameters are saved to the view data:

<Br/> [TestMethod] <br/> public void TestFakeFormParams () <br/>{< br/> // Create controller <br/> var controller = new HomeController (); <br/> // Create fake controller context <br/> var formParams = new NameValueCollection {"firstName", "Stephen"}, {"lastName ", "Walther" }}; <br/> controller. controllerContext = new FakeControllerContext (controller, formParams); <br/> // Act <br/> var result = controller. insert () as ViewResult; <br/> Assert. areEqual ("Stephen", result. viewData ["firstName"]); <br/> Assert. areEqual ("Walther", result. viewData ["lastName"]); <br/>}< br/>

The form parameters of FakeControllerContext are created through a NameValueCollection. The Imitation set of form parameters is passed to the constructor of FakeControllerContext.

Test query string Parameters

Suppose you need to test whether the query string parameter is passed to a view. Query strings can be directly accessed through the Request. QueryString collection. For example, the Controller operation may look like the following:

<Br/> public ViewResult Details () <br/> {<br/> ViewData ["key1"] = Request. queryString ["key1"]; <br/> ViewData ["key2"] = Request. queryString ["key2"]; <br/> ViewData ["count"] = Request. queryString. count; <br/> return View (); <br/>}< br/>

In this case, you can copy the query string by passing a NameValueCollection to the FakeControllerContext constructor:

<Br/> [TestMethod] <br/> public void TestFakeQueryStringParams () <br/>{< br/> // Create controller <br/> var controller = new HomeController (); <br/> // Create fake controller context <br/> var queryStringParams = new NameValueCollection {"key1", "a" },{ "key2 ", "B" }}; <br/> controller. controllerContext = new FakeControllerContext (controller, null, queryStringParams); <br/> // Act <br/> var result = controller. details () as ViewResult; <br/> Assert. areEqual ("a", result. viewData ["key1"]); <br/> Assert. areEqual ("B", result. viewData ["key2"]); <br/> Assert. areEqual (queryStringParams. count, result. viewData ["count"]); <br/>}< br/>

Note that the query string must be passed in as the second parameter of the FakeControllerContext constructor.

Test user

You may need to test the security of controller operations. For example, you may want to display only a view for a specific authenticated user. The following controller operation shows a Secret view for verified users and redirects all other users to the Index view:

<Br/> public ActionResult Secret () <br/>{< br/> if (User. identity. isAuthenticated) <br/>{< br/> ViewData ["userName"] = User. identity. name; <br/> return View ("Secret "); <br/>}< br/> else <br/> {<br/> return RedirectToAction ("Index "); <br/>}< br/>

You can use FakeController to test whether the operation behavior is as expected:

<Br/> [TestMethod] <br/> public void TestFakeUser () <br/>{< br/> // Create controller <br/> var controller = new HomeController (); </p> <p> // Check what happens for authenticated user <br/> controller. controllerContext = new FakeControllerContext (controller, "Stephen"); <br/> var result = controller. secret () as ActionResult; <br/> Assert. isInstanceOfType (result, typeof (ViewResult); <br/> ViewDataDictionary viewData = (ViewResult) result ). viewData; <br/> Assert. areEqual ("Stephen", viewData ["userName"]); </p> <p> // Check what happens for anonymous user <br/> controller. controllerContext = new FakeControllerContext (controller); <br/> result = controller. secret () as ActionResult; <br/> Assert. isInstanceOfType (result, typeof (RedirectToRouteResult); <br/>}< br/>

This test actually tests three things (maybe it should be divided into multiple tests ). First, it tests a view to verify whether the user has obtained the required view from the Controller operation. Secondly, it tests whether the user name verified has been successfully added to the attempted data. Finally, it checks whether anonymous users are redirected when controlling their operations.

Test User Roles

You may want to display different content for different users based on different roles. For example, some content can only be viewed by the Administrator (Admins. Assume that you have a controller operation similar to the following:

<Br/> public ActionResult Admin () <br/>{< br/> if (User. isInRole ("Admin") <br/>{< br/> return View ("Secret "); <br/>}< br/> else <br/> {<br/> return RedirectToAction ("Index "); <br/>}< br/>

If you are a member with the Admin role, the Controller operation will return the Secret view.

You can test the Controller operation using the following test method:

<Br/> [TestMethod] <br/> public void TestFakeUserRoles () <br/>{< br/> // Create controller <br/> var controller = new HomeController (); </p> <p> // Check what happens for Admin user <br/> controller. controllerContext = new FakeControllerContext (controller, "Stephen", new string [] {"Admin"}); <br/> var result = controller. admin () as ActionResult; <br/> Assert. isInstanceOfType (result, typeof (ViewResult); </p> <p> // Check what happens for anonymous user <br/> controller. controllerContext = new FakeControllerContext (controller); <br/> result = controller. admin () as ActionResult; <br/> Assert. isInstanceOfType (result, typeof (RedirectToRouteResult); <br/>}< br/>

This operation verifies that only members of the Admin role can view the Secret view. The test also checks whether anonymous users are redirected to other pages.

Test browser Cookies

Suppose you need to test the access to the browser Cookies. For example, you may pass a customer ID through Cookies on the browser. How to test such operations?

The following Controller Method adds a browser Cookie to the view data:

<Br/> public ViewResult TestCookie () <br/> {<br/> ViewData ["key"] = Request. cookies ["key"]. value; <br/> return View (); <br/>}< br/>

You can test the Controller operation by creating a SessionItemCollection and passing it to FakeControllerContext:

<Br/> [TestMethod] <br/> public void TestCookies () <br/>{< br/> // Create controller <br/> var controller = new HomeController (); </p> <p> // Create fake Controller Context <br/> var cookies = new HttpCookieCollection (); <br/> cookies. add (new HttpCookie ("key", "a"); <br/> controller. controllerContext = new FakeControllerContext (controller, cookies); <br/> var result = controller. testCookie () as ViewResult; </p> <p> // Assert <br/> Assert. areEqual ("a", result. viewData ["key"]); <br/>}< br/>

This test verifies whether the Cookie named key is added to the view data by knowing its operation.

Test session Status

The last example is provided. Let's take a look at the Controller operation that has accessed the session Status:

<Br/> public ViewResult TestSession () <br/> {<br/> ViewData ["item1"] = Session ["item1"]; <br/> Session ["item2"] = "cool! "; <Br/> return View (); <br/>}< br/>

The Controller simultaneously reads and writes session states. It extracts an entry named item1 from the session state and adds it to the attempted data. The Controller operation also creates a session state entry named item2.

Use the following unit test to test the Controller operation:

<Br/> [TestMethod] <br/> public void TestSessionState () <br/>{< br/> // Create controller <br/> var controller = new HomeController (); </p> <p> // Create fake Controller Context <br/> var sessionItems = new SessionStateItemCollection (); <br/> sessionItems ["item1"] = "wow! "; <Br/> controller. controllerContext = new FakeControllerContext (controller, sessionItems); <br/> var result = controller. testSession () as ViewResult; </p> <p> // Assert <br/> Assert. areEqual ("wow! ", Result. ViewData [" item1 "]); </p> <p> // Assert <br/> Assert. AreEqual (" cool! ", Controller. HttpContext. Session [" item2 "]); <br/>}< br/>

Note that a SessionStateItemCollection is created and passed to the constructor of FakeControllerContext. SessionStateItemCollection indicates all entries in the session state.

Summary

In this Tip, I introduced how to test ASP. NET internal objects-such as form parameters, query strings, user entities, user roles, Cookies, and session statuses-use a set of standard imitation classes. You can download the complete code of these imitation classes through the following link (both C # and VB. NET code ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.