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

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. bootstrap table 自己设置值

    在使用bootstrap table的值默认是从 total rows 里面取,可是后台返回的json数据并不是这样的怎么办 可以使用 responseHandler  自定义: $(function ...

  2. Beaglebone Black教程Beaglebone Black中的Cloud9 IDE基本使用

    Beaglebone Black教程Beaglebone Black中的Cloud9 IDE基本使用 ​Beaglebone Black中的Cloud9 IDE基本使用 Cloud9是集成在Beagl ...

  3. git学习(六):git stash

    对于更改操作的处理 使用git status命令可以看到当前工作区的状态: git status // 查看工作区的状态 // 对于已经git add工作区中文件 git reset HEAD < ...

  4. 15.5.26-linq to ef多级外链查询

    方法一: var query = db.Test.Where(x => true) .Include(x => x.ColB.Select(s => s.ColBRelated)) ...

  5. SpringBoot 中常用注解@Controller/@RestController/@RequestMapping的区别

    SpringBoot中常用注解@Controller/@RestController/@RequestMapping的区别 @Controller 处理http请求 @Controller //@Re ...

  6. 宏晶STC单片机使用STC-ISP串口烧录失败的原因与解决方法汇总

    官方网址: http://www.stcisp.com/q_and_a_stcisp.html 个人小结 芯片:STC12C5A60S2 封装:LQFP-48 晶振大小:SD22.1184M 最小系统 ...

  7. ES6之函数参数

    ES6中对于函数参数主要增加了以下内容: 1.参数的扩展/数组的展开: 2.默认参数. 什么是参数的扩展? 看下面代码: <!DOCTYPE html> <html lang=&qu ...

  8. Java设计模式(1)工厂模式(Factory模式)

    工厂模式定义:提供创建对象的接口. 为何使用工厂模式 工厂模式是我们最常用的模式了,著名的Jive论坛,就大量使用了工厂模式,工厂模式在Java程序系统可以说是随处可见. 为什么工厂模式是如此常用?因 ...

  9. android 避免线程的重复创建(HandlerThread、线程池)

    最近在android开发中,用到都是new Thread(){...}.start()这种方式.本来这样是可以,但是最近突然爆出Performing stop of activity that is ...

  10. DPI (深度报文检测) 关于DPI的学习笔记

    关于DPI的学习笔记 先看一下定义 : DPI(Deep Packet Inspection)是一种基于数据包的深度检测技术,针对不同的网络应用层载荷(例如HTTP.DNS等)进行深度检测,通过对报文 ...