开发者

Create csv file as a StreamReader on the fly

I would like to unit test the following method

public IEnumerable<T> GetData<T>(S开发者_如何学CtreamReader 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

http://www.codeproject.com/KB/linq/LINQtoCSV.aspx


Sure:

var buffer = Encoding.Default.GetBytes("ab;cd;ef");
using (var stream = new MemoryStream(buffer))
using (var reader = new StreamReader(stream))
{
    var actual = GetData<SomeClass>(reader);
    // TODO: assert on actual
}


In your test, you could pass the method a StreamReader that reads from a MemoryStream instead of from a file or FileStream. The MemoryStream in turn can be populated with content that resembles the file contents during the test arrangement.


Ideally, change the signature to:

public IEnumerable<T> GetData<T>(TextReader fileStream) where T : new()

Then you can pass in a StringReader really easily.

Alternatives:

  • Have sample files embedded in your test assembly, fetch streams with Assembly.GetManifestResourceStream() and create a StreamReader from that
  • Use Encoding.GetBytes(text) and wrap the result in a MemoryStream, then build a StreamReader over that

For short tests, I would go with the StringReader version. For more data, embedding a file in your test assembly works really well.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜