user20358
user20358

Reputation: 14756

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. I cannot change the method signature. How does one test a method like this? I am using Nunit for testing.

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

Upvotes: 1

Views: 893

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100545

You need to Close/Flush/Dispose writer so it actually commits changes to stream:

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

Upvotes: 3

Related Questions