单元测试文件 I/O

单元测试文件 I/O

问题描述:

阅读 Stack Overflow 上现有的与单元测试相关的线程,我找不到关于如何对文件 I/O 操作进行单元测试的明确答案.我最近才开始研究单元测试,之前已经意识到它的优点,但很难习惯先编写测试.我已将我的项目设置为使用 NUnit 和 Rhino Mocks,虽然我了解它们背​​后的概念,但我在理解如何使用 Mock 对象时遇到了一些麻烦.

Reading through the existing unit testing related threads here on Stack Overflow, I couldn't find one with a clear answer about how to unit test file I/O operations. I have only recently started looking into unit testing, having been previously aware of the advantages but having difficulty getting used to writing tests first. I have set up my project to use NUnit and Rhino Mocks and although I understand the concept behind them, I'm having a little trouble understanding how to use Mock Objects.

具体来说,我有两个问题想要回答.首先,单元测试文件 I/O 操作的正确方法是什么?其次,在我尝试学习单元测试的过程中,我遇到了依赖注入.在设置并运行 Ninject 之后,我想知道我是否应该在单元测试中使用 DI,或者直接实例化对象.

Specifically I have two questions that I would like answered. First, what is the proper way to unit test file I/O operations? Second, in my attempts to learn about unit testing, I have come across dependency injection. After getting Ninject set up and working, I was wondering whether I should use DI within my unit tests, or just instantiate objects directly.

查看 TDD 教程 使用 Rhino MocksSystemWrapper.

Check out Tutorial to TDD using Rhino Mocks and SystemWrapper.

SystemWrapper 包装了许多 System.IO 类,包括 File、FileInfo、Directory、DirectoryInfo 等.您可以查看完整列表.

SystemWrapper wraps many of System.IO classes including File, FileInfo, Directory, DirectoryInfo, ... . You can see the complete list.

在本教程中,我将展示如何使用 MbUnit 进行测试,但它与 NUnit 完全相同.

In this tutorial I'm showing how to do testing with MbUnit but it's exactly the same for NUnit.

您的测试将如下所示:

[Test]
public void When_try_to_create_directory_that_already_exists_return_false()
{
    var directoryInfoStub = MockRepository.GenerateStub<IDirectoryInfoWrap>();
    directoryInfoStub.Stub(x => x.Exists).Return(true);
    Assert.AreEqual(false, new DirectoryInfoSample().TryToCreateDirectory(directoryInfoStub));

    directoryInfoStub.AssertWasNotCalled(x => x.Create());
}