使用Fakes的Stub和Shim对ASP.NET MVC4进行单元测试
这是一篇导航文,不是翻译。
MSDN对stub和shim的解释和使用场景演示:http://msdn.microsoft.com/en-us/library/hh549175.aspx
一个更详细的示例:http://www.richonsoftware.com/post/2012/04/05/Using-Stubs-and-Shim-to-Test-with-Microsoft-Fakes-in-Visual-Studio-11.aspx
我感兴趣的是如何对mvc项目进行测试:http://www.richonsoftware.com/post/2012/05/02/Noninvasive-Unit-Testing-in-ASPNET-MVC-A-Microsoft-Fakes-Deep-Dive.aspx
里面讲的内容分别有:
1,利用shim来重写第三方类库或系统类库的方法
[TestMethod]
public void TestLogOff()
{
var accountController = new AccountController();
var formsAuthenticationSignOutCalled = false;
RedirectToRouteResult redirectToRouteResult; //Scope the detours we're creating
using (ShimsContext.Create())
{
//Detours FormsAuthentication.SignOut() to an empty implementation
ShimFormsAuthentication.SignOut = () =>
{
//Set a boolean to identify that we actually got here
formsAuthenticationSignOutCalled = true;
};
redirectToRouteResult = accountController.LogOff() as RedirectToRouteResult;
Assert.AreEqual(true, formsAuthenticationSignOutCalled);
} Assert.NotNull(redirectToRouteResult);
Assert.AreEqual("Index", redirectToRouteResult.RouteValues["Action"]);
Assert.AreEqual("Home", redirectToRouteResult.RouteValues["controller"]);
}
2,怎么判断该用stub
[TestMethod]
public void TestLogin()
{
string testUserName = "TestUserName";
string testPassword = "TestPassword";
bool testRememberMe = false;
string returnUrl = "/foo.html"; var loginModel = new LoginModel
{
UserName = testUserName,
Password = testPassword,
RememberMe = testRememberMe
}; var accountController = new AccountController(); //Setup underpinning via stubbing such that UrlHelper
//can validate that our "foo.html" is local
var stubHttpContext = new StubHttpContextBase();
var stubHttpRequestBase = new StubHttpRequestBase();
stubHttpContext.RequestGet = () => stubHttpRequestBase;
var requestContext = new RequestContext(stubHttpContext, new RouteData());
accountController.Url = new UrlHelper(requestContext); RedirectResult redirectResult;
//Scope the detours we're creating
using (ShimsContext.Create())
{
//Sets up a detour for Membership.ValidateUser to our mocked implementation
ShimMembership.ValidateUserStringString = (userName, password) =>
{
Assert.AreEqual(testUserName, userName);
Assert.AreEqual(testPassword, password);
return true;
}; //Sets up a detour for FormsAuthentication.SetAuthCookie to our mocked implementation
ShimFormsAuthentication.SetAuthCookieStringBoolean = (userName, rememberMe) =>
{
Assert.AreEqual(testUserName, userName);
Assert.AreEqual(testRememberMe, rememberMe);
}; redirectResult = accountController.Login(loginModel, returnUrl) as RedirectResult;
} Assert.NotNull(redirectResult);
Assert.AreEqual(redirectResult.Url, returnUrl);
}
3,如何还原动态对象
[TestMethod]
public void TestInvalidJsonLogin()
{
string testUserName = "TestUserName";
string testPassword = "TestPassword";
bool testRememberMe = false;
string testReturnUrl = "TestReturnUrl"; var loginModel = new LoginModel
{
UserName = testUserName,
Password = testPassword,
RememberMe = testRememberMe
}; var accountController = new AccountController();
JsonResult jsonResult;
//Scope the detours we're creating
using (ShimsContext.Create())
{
//Sets up a detour for Membership.ValidateUser to our mocked implementation
ShimMembership.ValidateUserStringString = (userName, password) => false;
jsonResult = accountController.JsonLogin(loginModel, testReturnUrl);
}
//答案在这里
var errors = (IEnumerable<string>)(new PrivateObject(jsonResult.Data, "errors")).Target;
Assert.AreEqual("The user name or password provided is incorrect.", errors.First());
4,如何给请求添加上下文,及如何在请求中加入用户对象
[TestMethod]
public void TestChangePassword()
{
string testUserName = "TestUserName";
string testOldPassword = "TestOldPassword";
string testNewPassword = "TestNewPassword"; var changePasswordModel = new ChangePasswordModel
{
OldPassword = testOldPassword,
NewPassword = testNewPassword
}; var accountController = new AccountController(); //Stub HttpContext
var stubHttpContext = new StubHttpContextBase();
//Setup ControllerContext so AccountController will use our stubHttpContext
accountController.ControllerContext = new ControllerContext(stubHttpContext,
new RouteData(), accountController); //Stub IPrincipal
var principal = new StubIPrincipal();
principal.IdentityGet = () =>
{
var identity = new StubIIdentity { NameGet = () => testUserName };
return identity;
};
stubHttpContext.UserGet = () => principal; RedirectToRouteResult redirectToRouteResult;
//Scope the detours we're creating
using (ShimsContext.Create())
{
ShimMembership.GetUserStringBoolean = (identityName, userIsOnline) =>
{
Assert.AreEqual(testUserName, identityName);
Assert.AreEqual(true, userIsOnline); var memberShipUser = new ShimMembershipUser();
//Sets up a detour for MemberShipUser.ChangePassword to our mocked implementation
memberShipUser.ChangePasswordStringString = (oldPassword, newPassword) =>
{
Assert.AreEqual(testOldPassword, oldPassword);
Assert.AreEqual(testNewPassword, newPassword);
return true;
};
return memberShipUser;
}; var actionResult = accountController.ChangePassword(changePasswordModel);
Assert.IsInstanceOf(typeof(RedirectToRouteResult), actionResult);
redirectToRouteResult = actionResult as RedirectToRouteResult;
}
Assert.NotNull(redirectToRouteResult);
Assert.AreEqual("ChangePasswordSuccess", redirectToRouteResult.RouteValues["Action"]);
}
上面种种,文章给的不仅仅是答案,更有思考过程,比如问题原因,可能的解决方法,以及最后给一个最优的方法,值得一读的。
使用Fakes的Stub和Shim对ASP.NET MVC4进行单元测试的更多相关文章
- ASP.NET 系列:单元测试
单元测试可以有效的可以在编码.设计.调试到重构等多方面显著提升我们的工作效率和质量.github上可供参考和学习的各种开源项目众多,NopCommerce.Orchard等以及微软的asp.net m ...
- ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存
ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存 part 1:给我点时间,允许我感慨一下2016年 正好有时间,总结一下最近使用的一些技术,也算是为2016年画上一个完 ...
- CentOS上 Mono 3.2.8运行ASP.NET MVC4经验
周一到周三,折腾了两天半的时间,经历几次周折,在小蝶惊鸿的鼎力帮助下,终于在Mono 3.2.8上运行成功MVC4.在此总结经验如下: 系统平台的版本: CentOS 6.5 Mono 3.2.8 J ...
- ASP.NET MVC4入门到精通系列目录汇总
序言 最近公司在招.NET程序员,我发现好多来公司面试的.NET程序员居然都没有 ASP.NET MVC项目经验,其中包括一些工作4.5年了,甚至8年10年的,许多人给我的感觉是:工作了4.5年,We ...
- [MVC4]ASP.NET MVC4+EF5(Lambda/Linq)读取数据
继续上一节初始ASP.NET MVC4,继续深入学习,感受了一下微软的MVC4+EF5(EntityFramework5)框架的强大,能够高效的开发出网站应用开发系统,下面就看一下如何用MVC4+EF ...
- 21、ASP.NET MVC入门到精通——ASP.NET MVC4优化
本系列目录:ASP.NET MVC4入门到精通系列目录汇总 删除无用的视图引擎 默认情况下,ASP.NET MVCE同时支持WebForm和Razor引擎,而我们通常在同一个项目中只用到了一种视图引擎 ...
- 最新版CentOS6.5上安装部署ASP.NET MVC4和WebApi
最新版CentOS6.5上安装部署ASP.NET MVC4和WebApi 使用Jexus5.8.1独立版 http://www.linuxdot.net/ ps:该“独立版”支持64位的CentOS ...
- Asp.Net MVC4 + Oracle + EasyUI 学习 第二章
Asp.Net MVC4 + Oracle + EasyUI 第二章 --使用Ajax提升网站性能 本文链接:http://www.cnblogs.com/likeli/p/4236723.html ...
- Asp.Net MVC4 + Oracle + EasyUI 学习 第一章
Asp.Net MVC4 + Oracle + EasyUI 第一章 --操作数据和验证 本文链接:http://www.cnblogs.com/likeli/p/4234238.html 文章集合 ...
随机推荐
- A. Counterexample (Codeforces Round #275(div2)
A. Counterexample time limit per test 1 second memory limit per test 256 megabytes input standard in ...
- mysql的导入导出工具mysqldump命令详解
导出要用到MySQL的mysqldump工具,基本用法是: shell> mysqldump [OPTIONS] database [tables] 如果你不给定任何表,整个数据库将被导出. 通 ...
- 从Unauthorized 401错误学习Spring Boot的Actuator
之前用Spring Boot都是别人搭好的框架,然后自己在里面写就行了.对原理.细节上都怎么涉及,毕竟需求都做不完.但是昨天一个访问RESTful接口的401问题搞了我2个小时.网上找的很多用: ma ...
- OKR
不得不佩服老外对概念的提炼能力.一套一套的. Mission Vision Strategic Objectives Key Results Tasks
- uboot下的网络终端/控制台
许多linux设备可能没有外置串口,这是就需要一个网络终端来在uboot下操作设备,如升级镜像等. uboot下的网络终端为netconsole,代码drivers/net/netconsole.c. ...
- WIN7或者WIN8上边框的异常问题的解决攻略
//主要两个步骤://第一个步骤就是在CMainFrame::OnCreate里面增加 HINSTANCE hInst = LoadLibrary(_T("UxTheme.dll" ...
- kafka集群中jmx端口设置
jmx端口主要用来监控kafka集群的. 在启动kafka的脚本kafka-server-start.sh中找到堆设置,添加export JMX_PORT="9999" if [ ...
- Redis哈希
Redis的哈希值是字符串字段和字符串值之间的映射,所以他们是表示对象的完美数据类型 在Redis中的哈希值,可存储超过400十亿键值对. 例子 redis 127.0.0.1:6379> HM ...
- 制作nodejs项目镜像,实现docker下的快速部署
前言 前面的文章<centos7+ docker1.12 实践部署docker及配置direct_lvm>中,已经实践了如何在centos7下安装,配置docker, 所以接下来就打算去制 ...
- 解决java.lang.IllegalStateException: The application’s PagerAdapter changed the adapter’s content
A界面中有viewpager的动态加载,从界面A跳到界面B,再finish掉B返回A时报出此异常. java.lang.IllegalStateException: The application's ...