C # Unit Test parameter StreamWriter

I have a bunch of classes that implement the interface, and one of the parameters is StreamWriter.

I need to check the contents of StreamWriter.

I am trying to find a way to avoid writing text files on a test server and opening them to check the contents.

Is there a way to quickly convert the contents / stream of a StreamWriter to a StringBuilder variable?

+7
source share
4 answers

You cannot check StreamWriter . You can check the underlying stream it writes to. That way you can use a MemoryStream in your unit test and point it to a StreamWriter . After he finishes writing, you can read it.

 [TestMethod] public void SomeMethod_Should_Write_Some_Expected_Output() { // arrange using (var stream = new MemoryStream()) using (var writer = new StreamWriter(stream)) { // act sut.SomeMethod(writer); // assert string actual = Encoding.UTF8.GetString(stream.ToArray()); Assert.AreEqual("some expected output", actual); } } 
+12
source

I would suggest you change the parameter to TextWriter , if at all possible - at this point you can use StringWriter .

Alternatively, you can create a StreamWriter around a MemoryStream and then check the contents of that MemoryStream later (either rewind it or just call ToArray() to get the full contents as a byte array. If you really want to test the text, it's definitely easier to use StringWriter .

+9
source

You can replace it with a StreamWriter, which writes to a MemoryStream.

+2
source

In this case, you need to make fun of a test case. You can use the frameworks that rhino mocks liked. This is an advantage of the mocking structure - you can check the contents of objects, but you do not need to hit the server or take server resources.

This link will provide you with basic examples: http://www.codeproject.com/Articles/10719/Introducing-Rhino-Mocks

+1
source

All Articles