Book Image

Practical Test-Driven Development using C# 7

By : John Callaway, Clayton Hunt
Book Image

Practical Test-Driven Development using C# 7

By: John Callaway, Clayton Hunt

Overview of this book

Test-Driven Development (TDD) is a methodology that helps you to write as little as code as possible to satisfy software requirements, and ensures that what you've written does what it's supposed to do. If you're looking for a practical resource on Test-Driven Development this is the book for you. You've found a practical end-to-end guide that will help you implement Test-Driven Techniques for your software development projects. You will learn from industry standard patterns and practices, and shift from a conventional approach to a modern and efficient software testing approach in C# and JavaScript. This book starts with the basics of TDD and the components of a simple unit test. Then we look at setting up the testing framework so that you can easily run your tests in your development environment. You will then see the importance of defining and testing boundaries, abstracting away third-party code (including the .NET Framework), and working with different types of test double such as spies, mocks, and fakes. Moving on, you will learn how to think like a TDD developer when it comes to application development. Next, you'll focus on writing tests for new/changing requirements and covering newly discovered bugs, along with how to test JavaScript applications and perform integration testing. You’ll also learn how to identify code that is inherently un-testable, and identify some of the major problems with legacy applications that weren’t written with testability in mind. By the end of the book, you’ll have all the TDD skills you'll need and you’ll be able to re-enter the world as a TDD expert!
Table of Contents (21 chapters)
Title Page
Packt Upsell
Foreword
Contributors
Preface
4
What to Know Before Getting Started
Index

Life sometimes hands you lemons


While I hope you never receive code this bad, we are going to walk through what is needed to turn even this into readable, maintainable, and fully tested code. The best part, the part you aren't going to believe, is that transforming this code is actually safe and fairly easy.

Getting started

In any code situation like this, the first thing we must do is remove the code in question from the environment where we have no control. In this case, we can't test the code if it is sitting in Program.main. So, let's grab the whole thing and put it into a class named Mastermind. We will have a single function named Play that will run the game. This is considered a safe refactoring, because we are not changing any of the existing code, simply moving it somewhere else.

In the file Program.cs:

class Program
{
  static void Main(string[] args)
  {
    var game = new Mastermind();
    game.Play(args);
  }
}

In the file Mastermind.cs:

class Mastermind
{
  public void Play(string...