本文转自: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 herethrownewNotImplementedException();}

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 herethrownewNotImplementedException();}

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]public 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. mvc移动创建oracle表,使用 ASP.NET MVC (C#)在15分钟内创建电影数据库应用程序 | Microsoft Docs...

    使用 ASP.NET MVC 在 15 分钟内创建电影数据库应用程序 (C#)Create a Movie Database Application in 15 Minutes with ASP.NE ...

  2. Professional C# 6 and .NET Core 1.0 - Chapter 41 ASP.NET MVC

    What's In This Chapter? Features of ASP.NET MVC 6 Routing Creating Controllers Creating Views Valida ...

  3. 基于ASP.NET MVC的ABP框架入门学习教程

    为什么使用ABP 我们近几年陆续开发了一些Web应用和桌面应用,需求或简单或复杂,实现或优雅或丑陋.一个基本的事实是:我们只是积累了一些经验或提高了对,NET的熟悉程度. 随着软件开发经验的不断增加, ...

  4. ASP.NET MVC: 构建不带 Web 窗体的 Web 应用程序(转载)

    我 从事专业开发迄今为止已有 15 年,在此之前,我利用业余时间从事开发至少也有 10 年了.与我这一代的大多数人一样,我是从 8 位计算机起步,然后转用 PC 平台的.随着计算机的复杂性日益增加,我 ...

  5. [译]Chapter 1 - An Introduction to ASP.NET MVC(2)

    原文地址:Chapter 1 - An Introduction to ASP.NET MVC Avoiding Code Smells 如果你不是很小心,软件程序很快就会变得很难对应变更.我们都曾经 ...

  6. ASP.NET MVC SportStore 购物网示例(6)

    定义一个订单提供 IoC 组件 在DomainModel项目中新建文件夹Services添加以下接口: namespace DomainModel.Services { public interfac ...

  7. ASP.NET MVC 2示例Tailspin Travel

    Tailspin Travel 是一个旅游预订的应用程序示例,最新版本采用ASP.NET MVC 2技术构建,主要使用 DataAnnotations 验证, 客户端验证和ViewModels,还展示 ...

  8. 我要学ASP.NET MVC 3.0(一): MVC 3.0 的新特性

    摘要 MVC经过其1.0和2.0版本的发展,现在已经到了3.0的领军时代,随着技术的不断改进,MVC也越来越成熟.使开发也变得简洁人性化艺术化. 园子里有很多大鸟都对MVC了如指掌,面对问题犹同孙悟空 ...

  9. EFMVC - ASP.NET MVC 3 and Entity Framework 4.1 Code First 项目介绍

    项目概述 使用ASP.NET MVC 3.Razor.EF Code First.Unity 2.0 等等技术,演示如何创建一个ASP.NET MVC 3 的范例应用程序. 相关技术帖子: 中文: 使 ...

最新文章

  1. 关闭图片 pycharm_博士大佬总结的Pycharm 常用快捷键思维导图,收藏!
  2. SAP QM初阶之维护检验计划时可以不用事先创建好检验特性主数据
  3. linux下mysql的备份_Linux下MySQL的备份与还原
  4. Oracle+BEA后的ESB
  5. suse 启动oracle11g,SuSe10下Oracle11g文件系统模式安装及配置、网络配置与连接
  6. C++ 二叉树深度优先遍历和广度优先遍历
  7. 【QT学习之路】Charts的简单使用
  8. 计算机网络管理工程师技术水平证书,计算机网络管理工程师技术水平证书有什么用...
  9. 解决IDEA编译(java找不到符号)问题
  10. 造成增长停滞的各种原因
  11. htmlcss笔记(更新版)
  12. AOSP、AOKP、CM的区别
  13. 什么是集成测试?集成测试方法有哪些?
  14. c语言关于break的程序,c语言break的用法
  15. Git下载代码--git clone命令
  16. 百度离破产只有30天
  17. 【标签】那些想读的书
  18. 微信公众号支付WeixinJSBridge
  19. 解决Xshell7安装后打不开的问题
  20. PHP基础知识 - PHP 使用 MySQLI

热门文章

  1. loadrunner中的c函数----从参数列表中取参数并与特定字符进行字符串比较。
  2. 机器学习平台跃迁,AI中台才是大势所趋
  3. 企业 SpringBoot 教程 (七)springboot开启声明式事务
  4. POJ 3461 还是两种方法
  5. 前端每日实战:108# 视频演示如何用 CSS 和 D3 创作一个抽象的黑白交叠动画
  6. NodeJs开发微信公众号(一)
  7. iOS 之 tableView的复用、设计模式
  8. Apache - AH00341
  9. Springboot-mongodb MongoRepository接口 save方法 详解
  10. mysql-主从服务器同步搭建