問題描述
是否有任何庫或方法可以在 C# 中模擬文件系統(tǒng)來編寫單元測試?在我目前的情況下,我有一些方法可以檢查某個文件是否存在并讀取創(chuàng)建日期.將來我可能需要更多.
Are there any libraries or methods to mock out the file system in C# to write unit tests? In my current case I have methods that check whether certain file exists and read the creation date. I may need more than that in future.
推薦答案
安裝 NuGet 包 System.IO.Abstractions
.
Install the NuGet package System.IO.Abstractions
.
最初接受此答案時,此包不存在.原始答案是針對以下歷史背景提供的:
This package did not exist when this answer was originally accepted. The original answer is provided for historical context below:
你可以通過創(chuàng)建一個界面來做到這一點:
You could do it by creating an interface:
interface IFileSystem {
bool FileExists(string fileName);
DateTime GetCreationDate(string fileName);
}
并創(chuàng)建一個真正的"實現(xiàn),它使用System.IO.File.Exists() 等.然后您可以使用模擬框架;我推薦 起訂量.
and creating a 'real' implementation which uses System.IO.File.Exists() etc. You can then mock this interface using a mocking framework; I recommend Moq.
有人這樣做了,請把它發(fā)布到網(wǎng)上這里.
somebody's done this and kindly posted it online here.
我已經(jīng)使用這種方法在 IClock 中模擬了 DateTime.UtcNow接口(對于我們的測試能夠控制真的非常有用時間的流動!),以及更傳統(tǒng)的 ISqlDataAccess界面.
I've used this approach to mock out DateTime.UtcNow in an IClock interface (really really useful for our testing to be able to control the flow of time!), and more traditionally, an ISqlDataAccess interface.
另一種方法可能是使用 TypeMock,這允許您攔截對類的調(diào)用并將它們存根.然而,這確實要花費錢,并且需要安裝在您整個團隊的 PC 上,并且為了運行您的構(gòu)建服務器,它顯然也不適用于System.IO.File,因為它 不能存根 mscorlib.
Another approach might be to use TypeMock, this allows you to intercept calls to classes and stub them out. This does however cost money, and would need to be installed on your whole team's PCs and your build server in order to run, also, it apparently won't work for the System.IO.File, as it can't stub mscorlib.
您也可以接受某些方法不可單元測試并在單獨的慢速集成/系統(tǒng)測試中測試它們套房.
You could also just accept that certain methods are not unit testable and test them in a separate slow-running integration/system tests suite.
這篇關于您如何在 C# 中模擬文件系統(tǒng)以進行單元測試?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!