“Hello World” - The TDD way?

前端 未结 10 878
感动是毒
感动是毒 2021-01-31 21:10

Well I have been thinking about this for a while, ever since I was introduced to TDD. Which would be the best way to build a \"Hello World\" application ? which would print \"H

10条回答
  •  佛祖请我去吃肉
    2021-01-31 21:55

    You need to hide the Console behind a interface. (This could be considered to be useful anyway)

    Write a Test

    [TestMethod]
    public void HelloWorld_WritesHelloWorldToConsole()
    {
      // Arrange
      IConsole consoleMock = MockRepository.CreateMock();
    
      // primitive injection of the console
      Program.Console = consoleMock;
    
      // Act
      Program.HelloWorld();
    
      // Assert
      consoleMock.AssertWasCalled(x => x.WriteLine("Hello World"));
    }
    

    Write the program

    public static class Program
    {
      public static IConsole Console { get; set; }
    
      // method that does the "logic"
      public static void HelloWorld()
      {
        Console.WriteLine("Hello World");
      }
    
      // setup real environment
      public static void Main()
      {
        Console = new RealConsoleImplementation();
        HelloWorld();
      }
    }
    

    Refactor to something more useful ;-)

提交回复
热议问题