I need to write a unit test for a method that takes a stream which comes from a txt file, I would like to do do something like this:
Stream s = GenerateStreamFromString("a,b \n c,d");
I need to write a unit test for a method that takes a stream which comes from a txt file, I would like to do do something like this:
Stream s = GenerateStreamFromString("a,b \n c,d");
Use the MemoryStream
class, calling Encoding.GetBytes
to turn your string into an array of bytes first.
Do you subsequently need a TextReader
on the stream? If so, you could supply a StringReader
directly, and bypass the MemoryStream
and Encoding
steps.
I think you can benefit from using a MemoryStream. You can fill it with the string bytes that you obtain by using the GetBytes method of the Encoding class.
You're looking for the StringReader
class.
Well, maybe not directly, but i bet you want to use that stream in some sort fo reader right? if so, then you could use that directly.
Try stringreader http://msdn.microsoft.com/en-us/library/system.io.stringreader.aspx
Also this blog has a few ideas as well: http://weblogs.asp.net/whaggard/archive/2004/09/23/233535.aspx
Here you go:
private Stream GenerateStreamFromString(String p)
{
Byte[] bytes = UTF8Encoding.GetBytes(p);
MemoryStream strm = new MemoryStream();
strm.Write(bytes, 0, bytes.Length);
return strm;
}
public Stream GenerateStreamFromString(string s)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
Don't forget to use Using:
using (Stream s = GenerateStreamFromString("a,b \n c,d"))
{
// ... Do stuff to stream
}