[英]unit testing a void method with StreamWriter as one of the parameters
I currently have a method like this 我目前有这样的方法
public void BusinessMethod(object value, StreamWriter sw)
{
//Calls a private method that converts the data in `value` to a custom formatted string variable `str`
string str = myPrivateMethod(value);
//write the string to stream
sw.Write(str);
}
I am trying to test this method using the approach mentioned here and have done exactly the same thing. 我试图使用这里提到的方法测试这个方法,并完成了完全相同的事情。 However, my
result
string comes back as an empty string. 但是,我的
result
字符串以空字符串形式返回。 I cannot change the method signature. 我无法更改方法签名。 How does one test a method like this?
如何测试这样的方法? I am using Nunit for testing.
我正在使用Nunit进行测试。
This is my test method 这是我的测试方法
[Test]
public void My_Test()
{
MyPoco dto = new MyPoco ();
//set up the dto properties here
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
{
sut.BusinessMethod(dto, writer);
string result = Encoding.UTF8.GetString(stream.ToArray());
}
}
You need to Close
/ Flush
/ Dispose
writer so it actually commits changes to stream: 您需要
Close
/ Flush
/ Dispose
writer,以便实际提交对流的更改:
using (var stream = new MemoryStream())
{
using (var writer = new StreamWriter(stream))
{
sut.BusinessMethod(dto, writer);
}
// moved outside of inner using to ensure writer stored content to stream
string result = Encoding.UTF8.GetString(stream.ToArray());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.