Mocking 'System.Console' behaviour

前端 未结 5 1921
南方客
南方客 2020-12-06 04:45

Is there a standard way of making a C# console application unit-testable by programming against an interface, rather than System.Console?

For example, using an ICons

5条回答
  •  隐瞒了意图╮
    2020-12-06 05:43

    This code will work if you use just one thread:

    [TestClass]
    public class MyTests
    {
        private StringBuilder output;
        private StringWriter tempOutputWriter;
        private TextWriter originalOutputWriter;
    
        [TestInitialize]
        public void InitializeTest()
        {
            this.originalOutputWriter = Console.Out;
            this.tempOutputWriter = new StringWriter();
            Console.SetOut(tempOutputWriter);
            this.output = tempOutputWriter.GetStringBuilder();
        }
    
        [TestCleanup]
        public void CleanupTest()
        {
            Console.SetOut(originalOutputWriter);
            this.tempOutputWriter.Dispose();
        }
    
        [TestMethod]
        public void Test1()
        {
            Program.Main(new string[] { "1", "2", "3" });
            string output = this.output.ToString();
            ...
            this.output.Clear();
        }
    
        [TestMethod]
        public void Test2()
        {
            Program.Main(new string[] { "4", "5", "6" });
            string output = this.output.ToString();
            ...
            this.output.Clear();
        }
    }
    

提交回复
热议问题