在ASP.NET Web 应用开发中,我们经常使用Moq来实现一些Mock对Controller,Action做单元测试。UnityAutoMoq是一个集成Unity and Moq的组件。您可以使用下面的Command-line在控制台安装它:
Install-Package UnityAutoMoq
假设有这样的Controller代码:
public class AccountController : BaseController { // // GET: /Account/LogOn [HttpGet] public ActionResult LogOn() { var request = this.ControllerContext.HttpContext.Request; if (request != null && !request.IsLocal) { //Additional logic may perform here //.... return View("LogOn"); } return new EmptyResult(); } }
先来看传统使用MOQ的代码是这样的:
///**Traditional approach**/ [TestMethod] public void LogOn_ActionExecutes_ReturnsLogonView() { //Arrange var context = new Mock<HttpContextBase>(); var request = new Mock<HttpRequestBase>(); request.Setup(r => r.IsLocal).Returns(() => false); context.Setup(c => c.Request).Returns(() => request.Object); var controllerContext = new ControllerContext { HttpContext = context.Object }; var sut = new AccountController { ControllerContext = controllerContext }; //Act var result = sut.LogOn() as ViewResult; //Assert Assert.AreEqual("LogOn", result.ViewName); }
看看下面的变化,第二个测试方法显式调用HttpContextBase
1: ///**UnityAutoMoq container - HttpContextBase**/
2: [TestMethod]
3: public void LogOn_ActionExecutes_ReturnsLogonView1()
4: {
5: //Arrange
6: var container = new UnityAutoMoqContainer();
7: var controllerContext = container.Resolve<ControllerContext>();
8: var sut = new AccountController { ControllerContext = controllerContext };
9:
10: //Act
11: var result = sut.LogOn() as ViewResult;
12:
13: //Assert
14: Assert.AreEqual("LogOn", result.ViewName);
15: }
16:
17: ///**UnityAutoMoq container - Explicit setup on HttpContextBase
18: [TestMethod]
19: public void LogOn_ActionExecutes_ReturnsLogonView2()
20: {
21: //Arrange
22: var container = new UnityAutoMoqContainer();
23:
24: var context = container.GetMock<HttpContextBase>();
25: context.SetupGet(request => request.Request).Returns(() => null);
26:
27: var controllerContext = container.Resolve<ControllerContext>();
28: controllerContext.HttpContext = context.Object;
29:
30: var sut = new AccountController { ControllerContext = controllerContext };
31:
32: //Act
33: //we get null/empty Results
34: var result = sut.LogOn() as EmptyResult;
35:
36: //Assert
37: Assert.IsInstanceOfType(result,typeof(EmptyResult));
38: }
你有注意到这样的让代码更加简洁了,不用写太多了Setup方法。 这一个开源的组件, 你可参考实现自己的组件。
希望对您开发有帮助。
你可能感兴趣的文章:
Asp.net MVC 3 RTM 源代码中单元测试帮助类
Asp.net MVC中使用Razor Generator实现View的单元测试
使用Moles框架实现HttpWebRequest与HttpWebResponse的单元测试
作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog。