IO扩展控件(System.IO.Abstractions)
刚看到这个Namespace的时候还以为是.Net Framework里自带的包,结果查了一圈无任何结果。
果断上Github,一击即中https://github.com/tathamoddie/System.IO.Abstractions
先翻译下开发者给出的简单说明,今后再慢慢使用
类似于System.Web.Abstractions的用法,System.IO也被扩展了,它能针对IO对象进行访问
Just like System.Web.Abstractions, but for System.IO. Yay for testable IO access!
只能用NuGet方式下载
NuGet only:
Install-PackageSystem.IO.Abstractions
如果有需要可以下载测试帮助包
and/or:
Install-PackageSystem.IO.Abstractions.TestingHelpers
本库最核心的2个文件是IFileSystem和FileSystem。使用IFileSystem.File.ReadAllText
等方法替换掉之前的File.ReadAllText等方法。其他API也基本完全相同,除了一些我们扩展和进行测试的方法。
At the core of the library is IFileSystem and FileSystem. Instead of calling methods like File.ReadAllText
directly, use IFileSystem.File.ReadAllText
. We have exactly the same API, except that ours is injectable and testable.
publicclassMyComponent{readonlyIFileSystemfileSystem;//<summary>CreateMyComponentwiththegivenfileSystemimplementation</summary>publicMyComponent(IFileSystemfileSystem){this.fileSystem=fileSystem;}///<summary>CreateMyComponent</summary>publicMyComponent():this(fileSystem:newFileSystem()//usedefaultimplementationwhichcallsSystem.IO){}publicvoidValidate(){foreach(vartextFileinfileSystem.Directory.GetFiles(@"c:\","*.txt",SearchOption.TopDirectoryOnly)){vartext=fileSystem.File.ReadAllText(textFile);if(text!="Testingisawesome.")thrownewNotSupportedException("Wecan'tgoontogether.It'snotme,it'syou.");}}}
这个库中还包含了一系列测试程序,来帮助你熟悉它。虽然它不是一个成熟的文件系统,但是它一定会给你带来帮助的。
The library also ships with a series of test helpers to save you from having to mock out every call, for basic scenarios. They are not a complete copy of a real-life file system, but they'll get you most of the way there.
[Test]publicvoidMyComponent_Validate_ShouldThrowNotSupportedExceptionIfTestingIsNotAwesome(){//ArrangevarfileSystem=newMockFileSystem(newDictionary<string,MockFileData>{{@"c:\myfile.txt",newMockFileData("Testingismeh.")},{@"c:\demo\jQuery.js",newMockFileData("somejs")},{@"c:\demo\p_w_picpath.gif",newMockFileData(newbyte[]{0x12,0x34,0x56,0xd2})}});varcomponent=newMyComponent(fileSystem);try{//Actcomponent.Validate();}catch(NotSupportedExceptionex){//AssertAssert.AreEqual("Wecan'tgoontogether.It'snotme,it'syou.",ex.Message);return;}Assert.Fail("Theexpectedexceptionwasnotthrown.");}
我们甚至支持把.NET框架里不可测试的类型加入到测试程序里
We even support casting from the .NET Framework's untestable types to our testable wrappers:
FileInfoSomeBadApiMethodThatReturnsFileInfo(){returnnewFileInfo("a");}voidMyFancyMethod(){vartestableFileInfo=(FileInfoBase)SomeBadApiMethodThatReturnsFileInfo();//...}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。