使用OpenFileDialog c#的单元测试文件读取方法
发布时间:2020-12-15 23:38:45 所属栏目:百科 来源:网络整理
导读:我有一个函数,它返回文本文件路径和文件内容: public static Tuplestring,string OpenTextFile(){ OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog .Filter = "Text |*.txt"; bool? accept = openFileDialog.ShowDialog(); if (acce
我有一个函数,它返回文本文件路径和文件内容:
public static Tuple<string,string> OpenTextFile() { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog .Filter = "Text |*.txt"; bool? accept = openFileDialog.ShowDialog(); if (accept == true) return Tuple.Create(File.ReadAllText(openFileDialog.FileName,Encoding.UTF8),openFileDialog.FileName); else return null; } 我如何单元测试文件读取?是否可以测试对话框显示? 解决方法
该方法与多个问题紧密相关. OpenFileDialog是一个UI问题,File是一个IO问题.这使得单独测试该方法的功能变得困难但并非不可能.
将这些问题提取到他们自己的抽象中. public interface IOpenFileDialog { string Filter { get; set; } bool? ShowDialog(); string FileName { get; set; } } public interface IFileSystem { string ReadAllText(string path,Encoding encoding = Encoding.UTF8); } 我还建议将该静态方法转换为服务方法 public interface ITextFileService { Tuple<string,string> OpenTextFile(); } 它的实现将取决于其他抽象 public class TextFileService : ITextFileService { readonly IOpenFileDialog openFileDialog; readonly IFileSystem file; public SUT(IOpenFileDialog openFileDialog,IFileSystem file) { this.openFileDialog = openFileDialog; this.file = file; } public Tuple<string,string> OpenTextFile() { openFileDialog.Filter = "Text |*.txt"; bool? accept = openFileDialog.ShowDialog(); if (accept.GetValueOrDefault(false)) return Tuple.Create(file.ReadAllText(openFileDialog.FileName,openFileDialog.FileName); else return null; } } 然后,依赖关系的实现将包含它们各自的关注点. 这也将允许在单独测试其家属时模拟/替换所有抽象. 以下是基于上述建议使用MSTest和Moq测试方法的示例. [TestMethod] public void _OpenTextFile_Should_Return_TextContext_And_FileName() { //Arrange var expectedFileContent = "Hellow World"; var expectedFileName = "filename.txt"; var fileSystem = new Mock<IFileSystem>(); fileSystem.Setup(_ => _.ReadAllText(expectedFileName,It.IsAny<Encoding>())) .Returns(expectedFileContent) .Verifiable(); var openFileDialog = new Mock<IOpenFileDialog>(); openFileDialog.Setup(_ => _.ShowDialog()).Returns(true).Verifiable(); openFileDialog.Setup(_ => _.FileName).Returns(expectedFileName).Verifiable(); var sut = new TextFileService(openFileDialog.Object,fileSystem.Object); //Act var actual = sut.OpenTextFile(); //Assert fileSystem.Verify(); openFileDialog.Verify(); Assert.AreEqual(expectedFileContent,actual.Item1); Assert.AreEqual(expectedFileName,actual.Item2); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 安装 – 我可以在不安装Nova的情况下安装OpenStack的Swift(
- GCC编译C语言程序完整演示
- C编译器优化传递的参数
- cocos2dx 3d开源项目 fantasyWarrior3D 从零走起 4 [Battle
- c – 最喜欢的Valgrind选项
- OpenCV FileStorage类读写XML/YML文件
- c# – 如何在我的asp.net项目中停止额外的语言文件夹?
- swift – Decrypted String总是返回Null
- ruby-on-rails – 使用simple_form构建选择日期和年份输入
- ruby-on-rails – Rails 5 devise_token_auth无法验证CSRF令