C# Unit Test a StreamWriter parameter

前端 未结 3 533
梦谈多话
梦谈多话 2021-01-04 09:28

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

3条回答
  •  星月不相逢
    2021-01-04 09:41

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

提交回复
热议问题