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

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

问题描述

我对单元测试还比较陌生。我已经在Ruby中编写了一个类,它接收一个文件,在给定的Regex模式中搜索该文件,替换它,然后将更改保存回文件。我希望能够为这种方法编写单元测试,但我不知道如何去做。有人可以告诉我,我们如何处理文件I / O的单元测试方法吗?

解决方案

看看这个如何单元测试将文件保存到磁盘?



基本上这个想法是一样的,FileSystem是你的类的依赖。所以引入一个可以在单元测试中被模拟的角色/接口(这样在单元测试时就没有依赖关系了);这个角色中的方法应该是FileSystem所需要的所有东西 -

Read $()作为一个字符串返回file_contents或者字符串[]
写入(file_contents)#同上

现在你可以使用模拟返回一个字符串数组 - 你的类可以处理这个数组。在生产代码中,角色的真正实现会碰到文件系统以返回行数组。


I am still relatively new to unit testing. I have written a class in Ruby that takes a file, searches through that file for a given Regex pattern, replaces it, then saves the changes back to the file. I want to be able to write unit tests for this method, but I don't know how I would go about doing that. Can somebody tell me how we unit test methods that deal with file i/o?

解决方案

Check out this How do I unit-test saving file to the disk?

Basically the idea is the same, the FileSystem is a dependency for your class. So introduce a Role/interface that can be mocked in your unit-tests (such that you have no dependency while unit-testing); the methods in the role should be all the stuff you need from the FileSystem -

Read()  # returns file_contents as a string or string[]
Write(file_contents) # same as above

Now you can use a mock to return a canned string array - your class can then process this array. In production code, the real implementation of the role would hit the filesystem to return the array of lines.

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

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