maverick maverick - 2 months ago 9
C# Question

what is happening in a simple test code

I have the following lines of code, and have looked up the methods and object definitions in Microsoft documentation, but I still do not understand how it works.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace HelloWorld.Tests
{
[TestClass]
public class WhenProgramRuns
{
private string _consoleOutput;
[TestInitialize]
public void Initialize()
{
var w = new System.IO.StringWriter();
Console.SetOut(w);
Program.Main(new string[0]);
_consoleOutput = w.GetStringBuilder().ToString().Trim();
}
[TestMethod]
public void SayHelloWorld()
{
Assert.AreEqual("Hello, World", _consoleOutput);
}
}
}


I do not understand how "w" will capture the result of the execution of Main and why the author of code passed a string [0] when he called Main.

Here is Main:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, World");
}
}
}

Answer

Well, let's split it to pieces:

I do not understand how "w" will capture the result of the execution of Main

Technically, it is incorrect to say that it'll capture the result of execution. Our w is an instance of StringWriter. It captures instance of underlying Stream that Console can use to output data (apart from using normal console screen). Console will use this w to work with its Stream and write output using it.

and why the author of code passed a string [0] when he called Main

Method main accepts string[] as parameter, so in order to invoke it we have to pass something and as we do not really need this arguments later, to pass an empty array would be ok.

So, the logic of execution is something like :

  1. Create StringWriter that can work with stream in Console class.
  2. Set console to use this stream with the StringWriter to output data
  3. Run the only overload of Main method with required parameter of string[]
  4. Get output by calling GetStringBuilder() on StringWriter and make it build string by invoking ToString()