以下对HttpPost来的表单进行处理的方法进行单元测试。
以下为方法的源代码
<SPAN style="WHITE-SPACE: pre"> </SPAN>[HttpPost] public ActionResult NewName() { ViewBag.Name = Request.Form["Name"]; return View(); } |
在提交来的View里有一个@Html.Editor("Name")的元素
下面是单元测试代码,使用moq进行模拟对象
<PRE class=html name="code"><SPAN style="WHITE-SPACE: pre"> </SPAN>[TestMethod()] public void NewNameTest() {</PRE><PRE class=html name="code"><SPAN style="WHITE-SPACE: pre"> </SPAN> // 1,准备Form,每个项要一一地进行列举 FormCollection form = new FormCollection(); form["Name"] = "zhong"; </PRE><PRE class=html name="code"><SPAN style="WHITE-SPACE: pre"> </SPAN> // 2,mock Request对象 var mockRequest = new Mock<HttpRequestBase>(); mockRequest.SetupGet(m => m.Form).Returns(form);<SPAN style="WHITE-SPACE: pre"> </SPAN>// 调用Request中Form的getter时,返回我们准备的form </PRE><PRE class=html name="code"><SPAN style="WHITE-SPACE: pre"> </SPAN> // 3,mock HttpContext对象 var mockContext = new Mock<HttpContextBase>(); mockContext.SetupGet(m => m.Request).Returns(mockRequest.Object); // 调用HttpContext中Request时,返回模拟的Request对象 </PRE><PRE class=html name="code"><SPAN style="WHITE-SPACE: pre"> </SPAN> // 4,实例化Controller对象 HomeController target = new HomeController(); target.ControllerContext = new ControllerContext(mockContext.Object, new RouteData(), target); // 将模拟HttpContext对象传给Controller // 5,执行要测试的方法 ViewResult actual; actual = target.NewName() as ViewResult; </PRE><PRE class=html name="code"><SPAN style="WHITE-SPACE: pre"> </SPAN> // 6,断言测试 Assert.AreEqual("zhong", actual.ViewBag.Name); }</PRE><BR> <BR> <P></P> <PRE></PRE> <BR> <P></P> |