日期:2014-05-17  浏览次数:20806 次

10.2Asp.net MVC各层使用TDD方式
Asp.net MVC各层使用TDD方式

Asp.net MVC的TDD
-测试Routes
-测试Controller
-测试View helpers
-测试Views

Testing Routes
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
routes.MapRoute(
“Default”,
“{controller}/{action}/{id}”,
new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }
);
}

HTTP 测试模拟器
Moq: http://code.google.com/p/moq
using System.Web;
using Moq;
using System.Web.Routing;
[TestMethod]
public void CanMapNormalControllerActionRoute()
{
//arrange
RouteCollection routes = new RouteCollection();//保证原子性
MvcApplication.RegisterRoutes(routes);
var httpContextMock = new Mock<HttpContextBase>();
httpContextMock.Expect(c => c.Request
.AppRelativeCurrentExecutionFilePath).Returns(“~/product/list”);//测试Controller product
//act
RouteData routeData = routes.GetRouteData(httpContextMock.Object);
//assert
Assert.IsNotNull(routeData, “Should have found the route”);
Assert.AreEqual(“product”, routeData.Values[“Controller”]);
Assert.AreEqual(“list”, routeData.Values[“action”]);
Assert.AreEqual(null, routeData.Values[“id”]);
}

Testing Controllers
public ActionResult Save(string value)
{
TempData[“TheValue”] = value;
//Pretend to save the value successfully.
return RedirectToAction(“Display”);
}
[TestMethod]
public void SaveStoresTempDataValueAndRedirectsToFoo()
{
//arrange
var controller = new HomeController();
//act
var result = controller.Save(“is 42”) as RedirectToRouteResult;
//assert
Assert.IsNotNull(result, “Expected the result to be a redirect”);
Assert.AreEqual(“is 42”, controller.TempData[“TheValue”];
Assert.AreEqual(“Display”, result.Values[“action”]);
}

Testing View helpers
using System;
using System.Collections.Generic;
using System.Web.Mvc;
public static class MyHelpers
{
public static MvcHtmlString UnorderedList<T>(this HtmlHelper html,
IEnumerable<T> items)
{
throw new NotImplementedException();
}}
[TestMethod]
public void UnorderedListWithNullHtmlThrowsArgumentException()
{
try{
MyHelpers.UnorderedList(null, new int[] { });
Assert.Fail();}
catch (ArgumentNullException)
{return;}}
//测试通不过 没有NullException

Testing Views
-不由TDD进行测试

用户体验

2011-4-23 12:30 danny