views:

264

answers:

4

Hi

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

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

+1  A: 

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.

Anders Fjeldstad
+1  A: 

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
}
Darin Dimitrov
+1  A: 

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.

Jon Skeet
A: 

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

Christo Fur