Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check output in MSTest unit test

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);
}
like image 407
Sarah Vessels Avatar asked Feb 19 '10 17:02

Sarah Vessels


1 Answers

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');
like image 182
JaredPar Avatar answered Oct 19 '22 22:10

JaredPar