C#单元测试StreamWriter参数 [英] C# Unit Test a StreamWriter parameter
问题描述
我有一堆都实现接口的类,其中一个参数是StreamWriter.
I have a bunch of classes that all implement an Interface and one of the parameters is a StreamWriter.
我需要检查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.
是否可以快速将StreamWriter的内容/流转换为StringBuilder变量?
Is there is a way to quickly convert the StreamWriter contents/stream to a StringBuilder variable?
推荐答案
您不能检查 StreamWriter
.您可以检查其正在写入的基础流.因此,您可以在单元测试中使用 MemoryStream
并将此 StreamWriter
指向它.完成编写后,您可以从中读取内容.
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);
}
}
这篇关于C#单元测试StreamWriter参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!