本文转自:http://www.asp.net/mvc/tutorials/older-versions/unit-testing/creating-unit-tests-for-asp-net-mvc-applications-cs

The goal of this tutorial is to demonstrate how you can write unit tests for the controllers in your ASP.NET MVC applications. We discuss how to build three different types of unit tests. You learn how to test the view returned by a controller action, how to test the View Data returned by a controller action, and how to test whether or not one controller action redirects you to a second controller action.

Creating the Controller under Test

Let’s start by creating the controller that we intend to test. The controller, named the ProductController, is contained in Listing 1.

Listing 1 – ProductController.cs

usingSystem;
usingSystem.Web.Mvc; namespace Store.Controllers{
public class ProductController:Controller{
public ActionResult Index(){
// Add action logic here
thrownewNotImplementedException();
} public ActionResult Details(intId){
returnView("Details");
} }
}

The ProductController contains two action methods named Index() and Details(). Both action methods return a view. Notice that the Details() action accepts a parameter named Id.

Testing the View returned by a Controller

Imagine that we want to test whether or not the ProductController returns the right view. We want to make sure that when the ProductController.Details() action is invoked, the Details view is returned. The test class in Listing 2 contains a unit test for testing the view returned by the ProductController.Details() action.

Listing 2 – ProductControllerTest.cs

using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Store.Controllers;
namespace StoreTests.Controllers{
[TestClass]
public class ProductControllerTest{
[TestMethod]
public void TestDetailsView(){
var controller =new ProductController();
var result = controller.Details(2)as ViewResult;
Assert.AreEqual("Details", result.ViewName);
}
}
}

The class in Listing 2 includes a test method named TestDetailsView(). This method contains three lines of code. The first line of code creates a new instance of the ProductController class. The second line of code invokes the controller’s Details() action method. Finally, the last line of code checks whether or not the view returned by the Details() action is the Details view.

The ViewResult.ViewName property represents the name of the view returned by a controller. One big warning about testing this property. There are two ways that a controller can return a view. A controller can explicitly return a view like this:

publicActionResultDetails(intId){returnView("Details");}

Alternatively, the name of the view can be inferred from the name of the controller action like this:

publicActionResultDetails(intId){returnView();}

This controller action also returns a view named Details. However, the name of the view is inferred from the action name. If you want to test the view name, then you must explicitly return the view name from the controller action.

You can run the unit test in Listing 2 by either entering the keyboard combination Ctrl-R, A or by clicking the Run All Tests in Solution button (see Figure 1). If the test passes, you’ll see the Test Results window in Figure 2.

Figure 01: Run All Tests in Solution (Click to view full-size image)

 

Figure 02: Success! (Click to view full-size image)

 

Testing the View Data returned by a Controller

An MVC controller passes data to a view by using something called View Data. For example, imagine that you want to display the details for a particular product when you invoke the ProductController Details() action. In that case, you can create an instance of a Product class (defined in your model) and pass the instance to the Details view by taking advantage of View Data.

The modified ProductController in Listing 3 includes an updated Details() action that returns a Product.

Listing 3 – ProductController.cs

using System;
using System.Web.Mvc; namespace Store.Controllers{ public class ProductController:Controller{ public ActionResult Index(){
// Add action logic here
thrownewNotImplementedException();
} public ActionResult Details(intId){
var product =new Product(Id,"Laptop");
return View("Details", product);
}
}
}

First, the Details() action creates a new instance of the Product class that represents a laptop computer. Next, the instance of the Product class is passed as the second parameter to the View() method.

You can write unit tests to test whether the expected data is contained in view data. The unit test in Listing 4 tests whether or not a Product representing a laptop computer is returned when you call the ProductController Details() action method.

Listing 4 – ProductControllerTest.cs

using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Store.Controllers; namespace StoreTests.Controllers{
[TestClass]
public class ProductControllerTest{
[TestMethod]
public void TestDetailsViewData(){
var controller =new ProductController();
var result = controller.Details(2) as ViewResult;
var product =(Product) result.ViewData.Model;
Assert.AreEqual("Laptop", product.Name);
}
}
}

In Listing 4, the TestDetailsView() method tests the View Data returned by invoking the Details() method. The ViewData is exposed as a property on the ViewResult returned by invoking the Details() method. The ViewData.Model property contains the product passed to the view. The test simply verifies that the product contained in the View Data has the name Laptop.

Testing the Action Result returned by a Controller

A more complex controller action might return different types of action results depending on the values of the parameters passed to the controller action. A controller action can return a variety of types of action results including a ViewResult, RedirectToRouteResult, or JsonResult.

For example, the modified Details() action in Listing 5 returns the Details view when you pass a valid product Id to the action. If you pass an invalid product Id -- an Id with a value less than 1 -- then you are redirected to the Index() action.

Listing 5 – ProductController.cs

using System;
using System.Web.Mvc;
namespace Store.Controllers{
public class ProductController:Controller{
public ActionResult Index(){
// Add action logic here
throw new NotImplementedException();
} public ActionResult Details(intId){
if(Id<1)
return RedirectToAction("Index");
var product =newProduct(Id,"Laptop");
returnView("Details", product);
}
}
}

You can test the behavior of the Details() action with the unit test in Listing 6. The unit test in Listing 6 verifies that you are redirected to the Index view when an Id with the value -1 is passed to the Details() method.

Listing 6 – ProductControllerTest.cs

using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Store.Controllers;
namespace StoreTests.Controllers{
[TestClass]p
ublic class ProductControllerTest{
[TestMethod]
public void TestDetailsRedirect(){
var controller =new ProductController();
var result =(RedirectToRouteResult) controller.Details(-1);
Assert.AreEqual("Index", result.Values["action"]);
}
}
}

When you call the RedirectToAction() method in a controller action, the controller action returns a RedirectToRouteResult. The test checks whether the RedirectToRouteResult will redirect the user to a controller action named Index.

Summary

In this tutorial, you learned how to build unit tests for MVC controller actions. First, you learned how to verify whether the right view is returned by a controller action. You learned how to use the ViewResult.ViewName property to verify the name of a view.

Next, we examined how you can test the contents of View Data. You learned how to check whether the right product was returned in View Data after calling a controller action.

Finally, we discussed how you can test whether different types of action results are returned from a controller action. You learned how to test whether a controller returns a ViewResult or a RedirectToRouteResult.

 

[转]Creating Unit Tests for ASP.NET MVC Applications (C#)的更多相关文章

  1. Custom Roles Based Access Control (RBAC) in ASP.NET MVC Applications - Part 1 (Framework Introduction)

    https://www.codeproject.com/Articles/875547/Custom-Roles-Based-Access-Control-RBAC-in-ASP-NET Introd ...

  2. 返璞归真 asp.net mvc (5) - Action Filter, UpdateModel, ModelBinder, Ajax, Unit Test

    原文:返璞归真 asp.net mvc (5) - Action Filter, UpdateModel, ModelBinder, Ajax, Unit Test [索引页] [源码下载] 返璞归真 ...

  3. 【转】ASP.NET MVC 的最佳实践

    [This post is based on a document authored by Ben Grover (a senior developer at Microsoft). It is ou ...

  4. [引]ASP.NET MVC 4 Content Map

    本文转自:http://msdn.microsoft.com/en-us/library/gg416514(v=vs.108).aspx The Model-View-Controller (MVC) ...

  5. Implementing HTTPS Everywhere in ASP.Net MVC application.

    Implementing HTTPS Everywhere in ASP.Net MVC application. HTTPS everywhere is a common theme of the ...

  6. 使用Metrics.NET 构建 ASP.NET MVC 应用程序的性能指标

    通常我们需要监测ASP.NET MVC 或 Web API 的应用程序的性能时,通常采用的是自定义性能计数器,性能计数器会引发无休止的运维问题(损坏的计数器.权限问题等).这篇文章向你介绍一个新的替代 ...

  7. Caching in ASP.NET MVC

    The caching options available in ASP.NET MVC applications don’t come from the ASP.NET MVC Framework, ...

  8. Mixing ASP.NET Webforms and ASP.NET MVC

    https://www.packtpub.com/books/content/mixing-aspnet-webforms-and-aspnet-mvc *********************** ...

  9. How to Choose the Best Way to Pass Multiple Models in ASP.NET MVC

    Snesh Prajapati, 8 Dec 2014 http://www.codeproject.com/Articles/717941/How-to-Choose-the-Best-Way-to ...

随机推荐

  1. MSP430看门狗

    其实430的看门狗,与51的大同小异,都是为了防止程序跑飞而出现不可预知的错误而专门设定的,所以说,看门狗的应用,是项目马上要进行实际应用中必须要进行的一环,也是电子工程师必须掌握的一环,下面介绍一下 ...

  2. oracle 启用归档日志

    Oracle可以运行在2种模式下:归档模式(archivelog)和非归档模式(noarchivelog) 归档模式可以提高Oracle数据库的可恢复性,生产数据库都应该运行在此模式下,归档模式应该和 ...

  3. Magento 前台的logo更改

    进入后台: 系统-配置, 然后选择左栏的“设计”, 选择右栏的“页眉”里面, 一般logo的路径在: skin/frontend/base/default/images/media/logo.png ...

  4. 2014-02-27WPF学习笔记

    //StackPanel布局 //创建时间:11:33 页面布局:Orientation默认纵向:Vertical水平为:Horizontal <Button> <Button.Co ...

  5. 【Kafka入门】搭建Kafka本地环境

    本博文介绍如何一步步搭建起Kafka本地环境. 下载Kafka 0.9.0.0 并配置软链接 下载好后,放入电脑本地安装目录,mac下我放在/usr/local下,解压Kafka. -0.9.0.0. ...

  6. 将COleDateTime类型数据转换成char *数据

    用OpenCV做多摄像头校准时间,在图像上显示时间信息,需求要将COleDateTime类型数据转换成char *数据 具体代码如下: 1: COleDateTime m_checkDate; 2: ...

  7. HDU 4497 GCD and LCM (数论)

    题意:三个数x, y, z. 给出最大公倍数g和最小公约数l.求满足条件的x,y,z有多少组. 题解:设n=g/l n=p1^n1*p2^n2...pn^nk (分解质因数 那么x = p1^x1 * ...

  8. 转(HP大中华区总裁孙振耀退休感言)

    开篇转发一篇好文,苦闷,消沉,寂寞,堕落的时候看看. 发现这篇文章是09年之前就有人转发到自己博客了.放到自己的地盘,容易记起有这么个心灵鸡汤.   一.关于工作与生活 我有个有趣的观察,外企公司多的 ...

  9. Vim Skills——Windows利用Vundle和Github进行Vim配置和插件的同步

    OS:Windows Vim安装完成之后,目录如下 vim73:vim运行时所需的文件,对应目录为$VIMRUNTIME变量 vimfiles:第三方的文件,对应目录为$VIM/vimfiles _v ...

  10. iOS新特性引导页

    有一个注意点: 获取版本号 个叫做Version,一个叫做Build,这两个值都可以在Xcode 中选中target,点击"Summary"后看到. Version在plist文件 ...