Mock Console

在一些特定的情况下我们需要来Mock console。 得到我们往Console写入的数据

public class ConsoleOutput : IDisposable
    {
        private StringWriter normalStringWriter;
        private TextWriter originalOut;
        private StringWriter errorStringWriter; //只是为了把 console的东西设回去。但是如果有多线程的情况就得加锁
        private TextWriter originalError;

        public ConsoleOutput()
        {
            normalStringWriter = new StringWriter();
            originalOut = Console.Out;
            Console.SetOut(normalStringWriter);

            originalError = Console.Error;
            errorStringWriter = new StringWriter();
            Console.SetError(errorStringWriter);
        }

        public string GetOuput()
        {
            return normalStringWriter.ToString();
        }

        public string GetError()
        {
            return errorStringWriter.ToString();
        }

        public void Dispose()
        {
            Console.SetOut(originalOut);
            Console.SetError(originalError);
            normalStringWriter.Dispose();
            errorStringWriter.Dispose();
        }
    }

使用

[Collection("console")] //防止并发
public class Test1
{
        [Fact]
        public void Test()
		{
			using (var co = new ConsoleOutput())
            {
                Console.WriteLine("aaaa");
                var result = co.GetOuput(); //这边可以得到数据的
            }
		}
}
下一篇:mock IMemoryCache
最近更新的
...