如何单元测试将文件保存到磁盘? [英] How do I unit-test saving file to the disk?
问题描述
我知道强烈建议运行单元测试与文件系统分离,因为如果你在测试中接触文件系统,你也测试文件系统本身.好的,这很合理.
我的问题是,如果我想测试文件保存到磁盘,我该怎么做?与数据库一样,我将负责数据库访问的接口分开,然后为我的测试创建另一个实现?或者可能有其他方式?
I know that it's strongly recommended to run unit-tests in separation from file system, because if you do touch file system in your test, you also test file system itself. OK, that's reasonable.
My question is, if I want to test file saving to the disk, what do I do? As with database, I separate an interface that is responsible for database access, and then create another implementation of this for my tests? Or may be there's some other way?
推荐答案
我对此的方法严重偏向于 由测试指导的成长型面向对象软件(GOOS)书,我刚读过,但它是我今天所知道的最好的.具体:
My approach towards this is heavily biased on the Growing Object-Oriented Software Guided by Tests (GOOS) book that I just read, but it's the best that I know of today. Specifically:
- 创建一个接口,从您的代码中抽象出文件系统.在需要这个类作为协作者/依赖项的地方模拟它.这使您的单元测试和反馈快速.
- 创建集成测试来测试接口的实际实现.即验证调用 Save() 实际上将文件持久化到磁盘并具有写入内容(使用参考文件或解析它以获取它应该包含的一些内容)
- 创建一个验收测试来测试整个系统 - 端到端.您可以在此处验证是否创建了文件 - 此测试的目的是确认实际实现是否正确连接/插入.
评论者更新:
如果您正在阅读结构化数据(例如 Book 对象)(如果不是用字符串替换 IEnumerable)
If you're reading structured data (e.g. Book objects) (If not substitute string for IEnumerable)
interface BookRepository
{
IEnumerable<Books> LoadFrom(string filePath);
void SaveTo(string filePath, IEnumerable<Books> books);
}
现在您可以使用构造函数注入将模拟注入客户端类.客户端类单元测试因此很快;不要点击文件系统.他们只是验证在依赖项上调用了正确的方法(例如加载/保存)
Now you can use constructor-injection to inject a mock into the client class. The client class unit tests therefore are fast ; do not hit the filesystem. They just verify that the right methods are called on the dependencies (e.g. Load/Save)
var testSubject = new Client(new Mock<BookRepository>.Object);
接下来,您需要创建 BookRepository 的真正实现,该实现可以处理文件(如果需要,也可以在明天创建 Sql DB).没有其他人需要知道.为 FileBasedBookRepository(实现上述角色)编写集成测试,并测试使用参考文件调用 Load 会提供正确的对象,并使用已知列表调用 Save,将它们持久化到磁盘.即使用真实文件这些测试会很慢,所以用标签标记它们或将其移到单独的套件中.
Next you need to create the real implementation of BookRepository that works off a File (or a Sql DB tommorrow if you want it). No one else has to know. Write integration tests for FileBasedBookRepository (that implements the above Role) and test that calling Load with a reference file gives the right objects and calling Save with a known list, persists them to the disk. i.e. uses real files These tests would be slow so mark them up with a tag or move it to a separate suite.
[TestFixture]
[Category("Integration - Slow")]
public class FileBasedBookRepository
{
[Test]
public void CanLoadBooksFromFileOnDisk() {...}
[Test]
public void CanWriteBooksToFileOnDisk() {...}
}
最后应该有一个/多个验收测试来练习加载和保存.
Finally there should be one/more acceptance tests that exercises Load and Save.
这篇关于如何单元测试将文件保存到磁盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!