单元测试文件I / O [英] Unit Testing File I/O

查看:148
本文介绍了单元测试文件I / O的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过这里对堆栈溢出现有的单元测试相关的主题阅读,我无法找到一个有关单位如何测试文件I / O操作一个明确的答案。我最近才开始寻找到单元测试,虽然已经previously意识到的优点,​​但有困难的习惯编写测试第一。我已经建立了我的项目使用NUnit的和犀牛制品,虽然我知道他们背后的概念,我有一个小麻烦了解如何使用模拟对象。

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.

推荐答案

查看<一个href=\"http://vkreynin.word$p$pss.com/2008/12/04/tutorial-to-tdd-using-rhino-mocks-and-systemwrapper/\">Tutorial以TDD 使用犀牛制品并的SystemWrapper

SystemWrapper包装许多System.IO类,包括文件,FileInfo的,目录和Dir​​ectoryInfo,...的。你可以看到完整列表

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.

您的测试将会是这个样子:

Your test is going to look something like this:

[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());
}

这篇关于单元测试文件I / O的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆