在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
概述
使用单元测试框架,Nunit。包括对controller的测试,以及moq框架的使用。
详解
1,数据库层Service的单元测试
引入:using NUnit.Framework;
[TestFixture] public class SystemConfigServiceTest { [Test] public void GetByIdTest() { SystemConfig configExcept = new SystemConfig(); configExcept.PkId = 78; SystemConfig configActual = new SystemConfigService().GetById(78); Assert.AreEqual(configExcept.PkId, configActual.PkId,"插叙编号为78的,如果测试不通过,请检查"); } }
类的特性标记为 TestFixture,要测试的方法特性标记为:Test,初始化测试对象,出入参数,判断返回值与你预期的值的比较。 这种测试是比较简单的单元测试。 2,Controller的单元测试 Moq 的介绍比较多http://www.cnblogs.com/haoliansheng/archive/2010/04/27/1721816.html
[Test] public void IndexFirstTest() { SystemConfigController controller = new SystemConfigController(); var httpContext = new Mock<HttpContextBase>(); var request = new Mock<HttpRequestBase>(); NameValueCollection queryString = new NameValueCollection(); queryString.Add("currentIndex", "1"); request.Setup(r => r.QueryString).Returns(queryString); httpContext.Setup(ht => ht.Request).Returns(request.Object); ControllerContext controllerContext = new ControllerContext(); controllerContext.HttpContext = httpContext.Object; controller.ControllerContext = controllerContext; //当前为19条记录,总共有4页 //第一页为5条记录 //Act ViewResult result1 = controller.Index(1, null) as ViewResult; //Assert ViewDataDictionary viewData1 = result1.ViewData; List<SystemConfig> model1 = viewData1.Model as List<SystemConfig>; //Assert.AreEqual(1, viewData1["CurrendIndex"],"单元测试的当前页为 ,第一页"); Assert.AreEqual(5, model1.Count, "第一页的长度应该为5,错误有可能是没有数据"); }
一个测试方法, var httpContext = new Mock<HttpContextBase>(); var request = new Mock<HttpRequestBase>(); 初始化两个对象,moq其实就是模拟两个对象。用他们来进行上下文的操作。 request.Setup(r => r.QueryString).Returns(queryString);初始化的过程 //第一页为5条记录 //Act ViewResult result1 = controller.Index(1, null) as ViewResult; 然后controller直接执行方法就可以了,在判断执行后的结果与预期的。
[Test] public void Index0Test() { SystemConfigController controller = new SystemConfigController(); var httpContext = new Mock<HttpContextBase>(); var request = new Mock<HttpRequestBase>(); NameValueCollection queryString = new NameValueCollection(); queryString.Add("currentIndex", "0"); request.Setup(r => r.QueryString).Returns(queryString); httpContext.Setup(ht => ht.Request).Returns(request.Object); ControllerContext controllerContext = new ControllerContext(); controllerContext.HttpContext = httpContext.Object; controller.ControllerContext = controllerContext; //第0页五条数据 ViewResult result3 = controller.Index(0, null) as ViewResult; ViewDataDictionary viewData3 = result3.ViewData; List<SystemConfig> model3 = viewData3.Model as List<SystemConfig>; //Assert.AreEqual(0, viewData3["CurrendIndex"]); Assert.AreEqual(5, model3.Count); }
技术要点 controller测试,moq框架的使用。
|
请发表评论