Check output in MSTest unit test

I want to capture the output sent to standard and standard errors in the MSTest unit test so that I can check it. I captured the output earlier when I explicitly started the Process , but is there a way to make [my option] the MSTest process itself? For example:

 [TestMethod] public void OutputTest() { MySnazzyMethod("input", 1, 'c'); string stdOutFromMySnazzyMethod = /* ??? */; Assert.AreEqual("expected output", stdOutFromMySnazzyMethod); } 
+6
c # stdout mstest
source share
4 answers

I liked the idea of JaredPar , but I did not want to go through Console.Out and Console.Error for every auxiliary output method that I had. However, my output goes through one class, so I just set a couple of static fields in it:

 internal static TextWriter _stdOut = Console.Out; internal static TextWriter _stdErr = Console.Error; 

I updated my output methods in the output handler class to use these fields. Then I updated this AssemblyInfo.cs project to include:

 [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("MyTestProject")] 

That way, I can override _stdOut and _stdErr in my testing methods, call my test method (which uses my output processing class) and confirm the expected result.

 OutputHandler._stdOut = new StringWriter(); MySnazzyMethod("input", 1, 'c'); OutputHandler._stdOut.Flush(); string expected = "expected output"; string stdout = OutputHandler._stdOut.ToString().Trim(new[] { '\r', '\n' }); Assert.IsFalse(string.IsNullOrEmpty(stdout)); Assert.AreEqual(expected, stdout); 
+3
source share

I'm not sure if there is a way to capture the output of an already running Process . What you could do is reorganize your code a bit so you don’t write in Console.WriteLine , but instead take an instance of TextWriter and write to it.

During production, you can simply pass the Console.Out method. In test code, you can make fun of 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'); 
+3
source share

Just add a pair of TraceListener to the class initialization of your test classes.

0
source share

I would use Moles to redirect the call to Console to write the lambda method inside your test code.

 string result = ""; System.Moles.MConsole.WriteLineString = (s) => { result = s; }; Assert.IsTrue(result == "The string I want", "Failed to write to console correctly"); 

See page 16 in this document: Roles Reference Guide .

0
source share

All Articles