If you want Unit Test Console , you probably need to create a shell interface.
public interface IConsole { string ReadLine(); } public class ConsoleWrapper : IConsole { public string ReadLine() { return Console.ReadLine(); } }
This way you can create Stub / Fake to test your business rules.
public class TestableConsole : IConsole { private readonly string _output; public TestableConsole(string output) { _output = output; } public string ReadLine() { return _output; } }
Inside the test:
public class TestClass { private readonly IConsole _console; public TestClass(IConsole console) { _console = console; } public void RunBusinessRules() { int value; if(!int.TryParse(_console.ReadLine(), out value) { throw new ArgumentException("User input was not valid"); } } } [Test] public void TestGettingInput() { var console = new TestableConsole("abc"); var classObject = new TestClass(console); Assert.Throws<ArgumentException>(() => classObject.RunBusinessRules()); }
I would try to avoid the Unit Testing Console and depend on it.
source share