剛看到這個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:
1 Install-Package System.IO.Abstractions
如果有需要可以下載測試幫助包
and/or:
1 Install-Package System.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.
1 public class MyComponent 2 { 3 readonly IFileSystem fileSystem; 4 5 // <summary>Create MyComponent with the given fileSystem implementation</summary> 6 public MyComponent(IFileSystem fileSystem) 7 { 8 this.fileSystem = fileSystem; 9 }
10 /// <summary>Create MyComponent</summary> 11 public MyComponent() : this(
12 fileSystem: new FileSystem() //use default implementation which calls System.IO 13 )
14 {
15 }
16 17 public void Validate()
18 {
19 foreach (var textFile in fileSystem.Directory.GetFiles(@"c:\", "*.txt", SearchOption.TopDirectoryOnly))
20 {
21 var text = fileSystem.File.ReadAllText(textFile);
22 if (text != "Testing is awesome.")
23 throw new NotSupportedException("We can't go on together. It's not me, it's you.");
24 }
25 }
26 }
這個庫中還包含了一系列測試程序,來幫助你熟悉它。雖然它不是一個成熟的文件系統,但是它一定會給你帶來幫助的。
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.
?1 [Test]??
2 public void MyComponent_Validate_ShouldThrowNotSupportedExceptionIfTestingIsNotAwesome() 3 { 4 // Arrange 5 var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> 6 { 7 { @"c:\myfile.txt", new MockFileData("Testing is meh.") }, 8 { @"c:\demo\jQuery.js", new MockFileData("some js") }, 9 { @"c:\demo\image.gif", new MockFileData(new byte[] { 0x12, 0x34, 0x56, 0xd2 }) }
10 });
11 var component = new MyComponent(fileSystem);
12 13 try 14 {
15 // Act 16 component.Validate();
17 }
18 catch (NotSupportedException ex)
19 {
20 // Assert 21 Assert.AreEqual("We can't go on together. It's not me, it's you.", ex.Message);
22 return;
23 }
24 25 Assert.Fail("The expected exception was not thrown.");
26 }
我們甚至支持把.NET框架里不可測試的類型加入到測試程序里
We even support casting from the .NET Framework's untestable types to our testable wrappers:
?1 FileInfo SomeBadApiMethodThatReturnsFileInfo()??
2 { 3 return new FileInfo("a"); 4 } 5 6 void MyFancyMethod() 7 { 8 var testableFileInfo = (FileInfoBase)SomeBadApiMethodThatReturnsFileInfo(); 9 //... 10 }