动态创建 csv 文件作为 StreamReader
我想对以下方法进行单元测试
public IEnumerable<T> GetData<T>(StreamReader fileStream) where T : new()
Streamreader 需要是 CSV 格式的文件,并具有特定的列名称。
是否可以在代码中创建此类文件,而不必在每个单元测试的文件系统上都包含大量此类文件?
有什么想法吗?
更新:
刚刚意识到我正在使用 Linq2Csv 的库,有方法可以做到这一点
I would like to unit test the following method
public IEnumerable<T> GetData<T>(StreamReader fileStream) where T : new()
The streamreader needs to be a file in CSV format, with particular column names.
Is it possible to create such files in code, rather than having to have lots of them on the file system for each unit test?
Any ideas?
UPDATE:
just realised the library I am using Linq2Csv, has methods for doing exactly this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当然:
Sure:
在测试中,您可以向该方法传递一个从
MemoryStream
而不是从文件或FileStream
读取的StreamReader
方法。反过来,MemoryStream
可以填充与测试安排期间的文件内容类似的内容。In your test, you could pass the method a
StreamReader
that reads from aMemoryStream
instead of from a file orFileStream
. TheMemoryStream
in turn can be populated with content that resembles the file contents during the test arrangement.理想情况下,将签名更改为:
然后您可以非常轻松地传入
StringReader
。替代方案:
Assembly.GetManifestResourceStream()
获取流,并从中创建一个StreamReader
Encoding.GetBytes(text)< /code> 并将结果包装在
MemoryStream
中,然后在其上构建一个 StreamReader对于简短的测试,我将使用
StringReader
版本。对于更多数据,在测试程序集中嵌入文件效果非常好。Ideally, change the signature to:
Then you can pass in a
StringReader
really easily.Alternatives:
Assembly.GetManifestResourceStream()
and create aStreamReader
from thatEncoding.GetBytes(text)
and wrap the result in aMemoryStream
, then build a StreamReader over thatFor short tests, I would go with the
StringReader
version. For more data, embedding a file in your test assembly works really well.刚刚意识到我正在使用 Linq2Csv 的库,有方法可以做到这一点
http://www .codeproject.com/KB/linq/LINQtoCSV.aspx
感谢您的回答
just realised the library I am using Linq2Csv, has methods for doing exactly this
http://www.codeproject.com/KB/linq/LINQtoCSV.aspx
thanks for the answers though