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

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

问题描述

在Stack Overflow上阅读现有的单元测试相关线程,我找不到有关如何单元测试文件I / O操作的明确答案。我最近刚刚开始研究单元测试,以前已经意识到这些优点,但是首先难以用来编写测试。我已经设置了我的项目来使用NUnit和Rhino Mocks,虽然我理解了他们的概念,但我有点麻烦了解如何使用Mock Objects。



具体我有两个问题,我想回答。首先,单元测试文件I / O操作的正确方法是什么?第二,在尝试了解单元测试时,我遇到了依赖注入。在Ninject设置和工作后,我想知道我是否应该在单元测试中使用DI,或者直接实例化对象。

解决方案

p>查看教程TDD ,使用 Rhino Mocks SystemWrapper



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



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



您的测试将会看起来像这样:

  [测试] 
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().TestToCreateDirectory(directoryInfoStub));

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


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.

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.

解决方案

Check out Tutorial to TDD using Rhino Mocks and SystemWrapper.

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

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天全站免登陆