MVC+UnitTest的单元测试
作者:网络转载 发布时间:[ 2015/3/12 13:24:10 ] 推荐标签:单元测试 软件测试
但是在内容中,发现没有添加POST和GET参数的方法,不太符合我自己的需求,所以自己在helper类中又添加了一个方法
1 /// <summary>
2 /// 创建HttpContextBase
3 /// </summary>
4 /// <returns></returns>
5 public static HttpContextBase CreateHttpContext(NameValueCollection PostParameter, NameValueCollection GetParameter)
6 {
7 var context = new Mock<HttpContextBase>();
8 var request = new Mock<HttpRequestBase>();
9 var response = new Mock<HttpResponseBase>();
10 var session = new Mock<HttpSessionStateBase>();
11 var server = new Mock<HttpServerUtilityBase>();
12
13 request.Setup(u => u.QueryString).Returns(GetParameter);
14
15 request.Setup(u => u.Form).Returns(PostParameter);
16 response
17 .Setup(rsp => rsp.ApplyAppPathModifier(Moq.It.IsAny<string>()))
18 .Returns((string s) => s);
19
20 context.Setup(ctx => ctx.Request).Returns(request.Object);
21 context.Setup(ctx => ctx.Response).Returns(response.Object);
22 context.Setup(ctx => ctx.Session).Returns(session.Object);
23 context.Setup(ctx => ctx.Server).Returns(server.Object);
24
25 return context.Object;
26 }
调用代码
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using BLL;
using COMMON;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using UI.Controllers;
namespace UiTest.Controllers
{
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void Index()
{
try
{
var homeController = new HomeController();
NameValueCollection post = new NameValueCollection();
post.Add("Version", "10");
NameValueCollection get = new NameValueCollection();
get.Add("bbb", "222");
HttpContextBase hcb = Common.MvcContextMockFactory.CreateHttpContext(post, get);
homeController.ControllerContext = Common.MvcContextMockFactory.CreateControllerContext(homeController,
hcb,
"~/Home/Index",
"get",
"DefaultRoute",
"{controller}/{action}",
null);
ViewResult result = (ViewResult) homeController.Index();
Assert.AreEqual("Index", result.ViewName);
}
catch (Exception ex)
{
Assert.IsFalse(true, ex.Message);
}
}
}
}
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11