Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Unit Test a StreamWriter parameter

I have a bunch of classes that all implement an Interface and one of the parameters is a StreamWriter.

I need to check the contents of the StreamWriter.

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

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

like image 906
Yogurt The Wise Avatar asked Sep 18 '12 15:09

Yogurt The Wise


2 Answers

You cannot check the StreamWriter. You could check the underlying stream it is writing to. So you could use a MemoryStream in your unit test and point this StreamWriter to it. Once it has finished writing you could read from 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);
    }
}
like image 102
Darin Dimitrov Avatar answered Nov 01 '22 21:11

Darin Dimitrov


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

Alternatively, you could create a StreamWriter around a MemoryStream, then test the contents of that MemoryStream later (either by rewinding it, or just calling ToArray() to get the complete contents as a byte array. If you really want to be testing text though, it's definitely simpler to use a StringWriter.

like image 37
Jon Skeet Avatar answered Nov 01 '22 21:11

Jon Skeet