I want to capture output sent to standard out and standard error within an MSTest unit test so that I can verify it. I've captured output before when explicitly running a Process
, but is there a way to do with [I guess] the MSTest process itself? For example:
[TestMethod]
public void OutputTest()
{
MySnazzyMethod("input", 1, 'c');
string stdOutFromMySnazzyMethod = /* ??? */;
Assert.AreEqual("expected output", stdOutFromMySnazzyMethod);
}
I'm not sure there is a way to grab the output of an already running Process
. What you could do though is refactor your code slightly to not write to Console.WriteLine
but instead take in a TextWriter
instance and write to that.
In production you can then just pass Console.Out
to the method. In test code you could mock this type and provide much more accurate testing. For example
[TestMethod]
public void OutputTest()
{
var writer = new Mock<TextWriter>(MockBehavior.Strict);
writer.Setup(x => x.WriteLine("expected output")).Verifiable();
MySnazzyMethod(writer.Object, "input", 1, 'c');
writer.Verify();
}
Production Code
MySnazzyMethod(Console.Out, "input", 1, 'c');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With