Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I suppose your <code>RunBankApplication</code> looks similar to this:</p> <pre><code>public void RunBankApplication() { var input = Console.ReadLine(); switch (input) { case "1": Console.WriteLine("Enter Account Number: "); break; case "2": Console.WriteLine("Hello World!"); break; default: break; } } </code></pre> <p>To get read of your fixed dependency on <code>Console</code> which makes your method untestable you should inject this dependency in constructor.</p> <p>You need an interface defining your dependency:</p> <pre><code>public interface IConsoleService { string ReadLine(); void WriteLine(string message); } </code></pre> <p>You create a default implementation for it:</p> <pre><code>public class ConsoleService : IConsoleService { public string ReadLine() { return Console.ReadLine(); } public void WriteLine(string message) { Console.WriteLine(message); } } </code></pre> <p>You then inject this implementation in your <code>BankManager</code> class and use it inside the class:</p> <pre><code>public class BankManager { private IConsoleService _consoleService; public BankManager(IConsoleService consoleService) { _consoleService = consoleService; } public void RunBankApplication() { var input = _consoleService.ReadLine(); switch (input) { case "1": _consoleService.WriteLine("Enter Account Number: "); break; case "2": _consoleService.WriteLine("Hello World!"); break; default: break; } } } </code></pre> <p>Now you can mock this dependency in your tests. <a href="http://code.google.com/p/moq/" rel="nofollow">Moq</a> is good choice of such a mocking library:</p> <pre><code>[TestClass] public class UnitTest1 { [TestMethod] public void GetMessage_Input1_ReturnEnterAccountNumberMessage() { var consoleService = new Mock&lt;IConsoleService&gt;(); consoleService.Setup(c =&gt; c.ReadLine()).Returns("1"); var bankManager = new BankManager(consoleService.Object); bankManager.RunBankApplication(); consoleService.Verify(c =&gt; c.WriteLine("Enter Account Number: "), Times.Once()); } [TestMethod] public void GetMessage_Input2_ReturnHelloWorldMessage() { var consoleService = new Mock&lt;IConsoleService&gt;(); consoleService.Setup(c =&gt; c.ReadLine()).Returns("2"); var bankManager = new BankManager(consoleService.Object); bankManager.RunBankApplication(); consoleService.Verify(c =&gt; c.WriteLine("Hello World!"), Times.Once()); } } </code></pre> <p>Sure, this is an overkill for such a simple example, but the approach is really useful in larger projects. As a next step you can then use an <a href="http://www.martinfowler.com/articles/injection.html" rel="nofollow">IoC container</a> to automatically inject your dependency in the application.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload