惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
月光博客
月光博客
T
Tailwind CSS Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
人人都是产品经理
人人都是产品经理
IT之家
IT之家
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
罗磊的独立博客
博客园 - 三生石上(FineUI控件)
有赞技术团队
有赞技术团队
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园_首页
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - Franky
The Cloudflare Blog
博客园 - 【当耐特】
Hugging Face - Blog
Hugging Face - Blog
大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
Jina AI
Jina AI
阮一峰的网络日志
阮一峰的网络日志
小众软件
小众软件
Last Week in AI
Last Week in AI

博客园 - 踏歌长行

前端知识质量内容网址 NuGet 质量博客链接 Entity Framework 质量博客链接 LINK1123:failure during conversion to COFF:file invalid or corrupt 未授权用户在此计算机上的请求登录类型 System.ServiceModel.AddressAccessDeniedException DataGrid 导出 Excel 中文乱码 80070005 Access is denied in Windows 2008 How to install ASP.NET 1.1 with IIS7 on Vista and Windows 2008 Unable to find script library '/aspnet_client/system-web/1-1-4322/webvalidation.js' JQuery file upload Access is denied in IE 7, 8, 9 ReportViewer 自适应高度 单元测试之 Xunit ASP.NET MVC ajax 提交列表到 Action VS 2010 制作 Windows Service 安装包之用户界面 VS 2010 制作 Windows Service 安装包 Postback 之后保持浏览器滚动条的位置 VS 2010 开发 ActiveX 自动升级外篇 VS 2010 开发 ActiveX 制作 cab 包
单元测试之模拟Mock
踏歌长行 · 2014-01-15 · via 博客园 - 踏歌长行



先看下面一段代码:

public class DataService : IDataService
{
        private readonly IDataRespository _dataRespository;
        public DataService(IDataRespository dataRespository)
        {
            _dataRespository = dataRespository;
        }

        public int GetCount()
        {
            var list = _dataRespository.GetList();
            return list.Count;
        }
}

其中有 GetCount() 方法是为获取列表的 Count,我们为这个方法写单元测试代码;GetCount() 中获取列表是调用了 IDataRespository 中的 GetList() 方法,此方法中的具体实现、返回的数据量我们都一无所知,所以为了测试 GetCount() 逻辑的正确性,必须对 GetList() 方法进行模拟。
1. 项目中引入Moq.dll
2. 具体如下

[Fact]
public void TestGetList()
{
            // 为 IDataRespository 创建模拟对象
            var mockDataRespository = new Mock<IDataRespository>();
            // 设置模拟对象的 GetList() 方法并设置返回值
            mockDataRespository.Setup(p => p.GetList()).Returns(() =>
                {
                    var list = new List<DataModel> {new DataModel()};

                    return list;
                });

            IDataService dataService = new DataService(mockDataRespository.Object);

            var actual = dataService.GetCount();
            const int expect = 1;

            Assert.Equal(expect, actual);
}