C# Unit Test a StreamWriter parameter

丶灬走出姿态 提交于 2019-12-30 05:58:09

问题


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?


回答1:


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);
    }
}



回答2:


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.




回答3:


You can replace it with a StreamWriter that writes to a MemoryStream.




回答4:


In that case you need to mock the test case. You can use frameworks likes rhino mocks. That advantage of mocking framework is, you can verify the contents of the objects, but you don't have to hit server or occupy server resources.

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



来源:https://stackoverflow.com/questions/12480563/c-sharp-unit-test-a-streamwriter-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!