用Java模拟文件 [英] Simulate File in Java

查看:67
本文介绍了用Java模拟文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为使用String文件名的方法编写单元测试,然后打开文件并从中读取文件.因此,为了测试该方法,我考虑过编写一个文件,然后调用我的方法.但是,在构建服务器场中,无法将文件任意写入磁盘.有没有一种标准方法可以在单元测试中模拟"真实文件?

I'm trying to write unit tests for a method that takes a String filename, then opens the file and reads from it. So, to test that method, I thought about writing a file, then calling my method. However, in the build farm, it is not possible to write files arbitrarily to disk. Is there a standard way to "simulate" having a real file in my unit test?

推荐答案

对此不以为然:

最少的可测试代码.通常是单个方法/功能,没有使用其他方法或类.快速地!千单位测试可以在十秒或更短的时间内运行!单元测试永远不要使用:

The smallest amount of testable code. Often a single method/function, sans the use of other methods or classes. Fast! Thousands of unit tests can run in ten seconds or less! A unit test NEVER uses:

  • 数据库
  • 应用服务器(或任何类型的服务器)
  • 文件/网络I/O或文件系统;
  • 另一个应用程序;
  • 控制台(System.out,System.err等)
  • 记录
  • 大多数其他类(例外包括DTO,String,Integer,mocks以及其他一些类)."

来源

如果必须从文件读取,请预先生成一个测试文件,以供所有单元测试读取.无需将任何内容写入磁盘.

If you must read from a file, have a test file pre-generated that all unit tests read from. There is no need to write anything to disk.

这篇关于用Java模拟文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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