这是一篇导航文,不是翻译。

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进行单元测试的更多相关文章

  1. ASP.NET 系列:单元测试

    单元测试可以有效的可以在编码.设计.调试到重构等多方面显著提升我们的工作效率和质量.github上可供参考和学习的各种开源项目众多,NopCommerce.Orchard等以及微软的asp.net m ...

  2. ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存

    ASP.Net MVC4+Memcached+CodeFirst实现分布式缓存 part 1:给我点时间,允许我感慨一下2016年 正好有时间,总结一下最近使用的一些技术,也算是为2016年画上一个完 ...

  3. CentOS上 Mono 3.2.8运行ASP.NET MVC4经验

    周一到周三,折腾了两天半的时间,经历几次周折,在小蝶惊鸿的鼎力帮助下,终于在Mono 3.2.8上运行成功MVC4.在此总结经验如下: 系统平台的版本: CentOS 6.5 Mono 3.2.8 J ...

  4. ASP.NET MVC4入门到精通系列目录汇总

    序言 最近公司在招.NET程序员,我发现好多来公司面试的.NET程序员居然都没有 ASP.NET MVC项目经验,其中包括一些工作4.5年了,甚至8年10年的,许多人给我的感觉是:工作了4.5年,We ...

  5. [MVC4]ASP.NET MVC4+EF5(Lambda/Linq)读取数据

    继续上一节初始ASP.NET MVC4,继续深入学习,感受了一下微软的MVC4+EF5(EntityFramework5)框架的强大,能够高效的开发出网站应用开发系统,下面就看一下如何用MVC4+EF ...

  6. 21、ASP.NET MVC入门到精通——ASP.NET MVC4优化

    本系列目录:ASP.NET MVC4入门到精通系列目录汇总 删除无用的视图引擎 默认情况下,ASP.NET MVCE同时支持WebForm和Razor引擎,而我们通常在同一个项目中只用到了一种视图引擎 ...

  7. 最新版CentOS6.5上安装部署ASP.NET MVC4和WebApi

    最新版CentOS6.5上安装部署ASP.NET MVC4和WebApi 使用Jexus5.8.1独立版 http://www.linuxdot.net/ ps:该“独立版”支持64位的CentOS ...

  8. Asp.Net MVC4 + Oracle + EasyUI 学习 第二章

    Asp.Net MVC4 + Oracle + EasyUI 第二章 --使用Ajax提升网站性能 本文链接:http://www.cnblogs.com/likeli/p/4236723.html ...

  9. Asp.Net MVC4 + Oracle + EasyUI 学习 第一章

    Asp.Net MVC4 + Oracle + EasyUI  第一章 --操作数据和验证 本文链接:http://www.cnblogs.com/likeli/p/4234238.html 文章集合 ...

随机推荐

  1. C#防止内存泄露的方法

    一般程序员()都会这样认为:用C#这样的语言编程的一个好处就是无需再考虑内存的分配和释放.你只需创建对象,然后通过一种叫做垃圾收集的机制来处理这 些对象,也就是说:当它们不再被应用程序需要的时候来自动 ...

  2. RabbitMQ文档翻译——Hello World!(下)

    Receiving That's it for our sender. Our receiver is pushed messages from RabbitMQ, so unlike the sen ...

  3. java读取配置文件内容

    利用com.typesafe.config包实现 <dependency> <groupId>com.typesafe</groupId> <artifact ...

  4. Android指南 - 样式和主题

    本文翻译自:https://developer.android.com/guide/topics/ui/themes.html Style和theme词汇是专用术语,下文直接使用而不翻译. 样式和主题 ...

  5. js android页面被挂起问题解决

    问题: 页面上设了定时器,但浏览器后台运行被挂起时,页面定时器暂停 解决: 向服务器发送同步请求,服务器延时1秒返回.页面收到返回时再次发送请求 服务器相当于起博器,维持页面将停的心跳

  6. 配置nginx

    咱不玩服务器,只在把人家的配置拷贝一份,建个自己的测试服务器 1. 如果nginx已配置(相当于windows在环境变量中配置了path吧) 查找nginx配置路径: whereis nginx 一般 ...

  7. MVC教程八:缓存过滤器

    缓存过滤器用来输出页面缓存,其用法如下图所示: 注意: Duration:表示缓存多少秒;VaryByParam:表示缓存是否随地址参数而改变.OutputCache除了可以定义在Action方法上面 ...

  8. thymeleaf传值onclick到js

    带有单引号 targetUrl('val') <a th:onclick="'javascript:targetUrl(\''+${indexURL.value}+'\');'&quo ...

  9. Matlab——plot polyfit polyval

    p=polyfit(x,y,m) 其中, x, y为已知数据点向量, 分别表示横,纵坐标, m为拟合多项式的次数, 结果返回m次拟合多项式系数, 从高次到低次存放在向量p中. y0=polyval(p ...

  10. STM32的TAMPER-RTC管脚作为Tamper的使用[转]

    问题一: 当 TAMPER引脚上的信号从 0变成1或者从 1变成 0(取决于备份控制寄存器BKP_CR的 TPAL位),会产生一个侵入检测事件.侵入检测事件将所有数据备份寄存器内容清除.   然而为了 ...