Practical Test-Driven Development using C# 7: Unleash the power of TDD by implementing real world examples under .NET environment and JavaScript
By John Callaway and Clayton Hunt
()
About this ebook
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!
Related to Practical Test-Driven Development using C# 7
Related ebooks
Instant Nancy Web Development: Leverage the powerful and lightweight .NET-based Nancy Web Framework Rating: 0 out of 5 stars0 ratingsC# 7 and .NET Core Cookbook Rating: 0 out of 5 stars0 ratingsJava Projects: Learn the fundamentals of Java 11 programming by building industry grade practical projects Rating: 0 out of 5 stars0 ratings12 Rules For Pro Coders: Pro Coder Series, #1 Rating: 0 out of 5 stars0 ratingsContinuous Delivery and DevOps - A Quickstart Guide: Start your journey to successful adoption of CD and DevOps Rating: 0 out of 5 stars0 ratingsMaster C# Interview Preparation: Dot Net Interview Preparation, #2 Rating: 0 out of 5 stars0 ratingsJava 9 Programming By Example Rating: 4 out of 5 stars4/5Learn React Hooks: Build and refactor modern React.js applications using Hooks Rating: 0 out of 5 stars0 ratingsWhat is Software Testing?: ISTQB Foundation Companion and Study Guide Rating: 5 out of 5 stars5/5Test-Driven Java Development, Second Edition: Invoke TDD principles for end-to-end application development Rating: 0 out of 5 stars0 ratingsFeature Flags: Transform Your Product Development Workflow Rating: 0 out of 5 stars0 ratingsHands-on Testing with PHPUnit How-to: A practical guide to getting started with PHPUnit to improve code quality Rating: 0 out of 5 stars0 ratingsDesign Patterns and Best Practices in Java: A comprehensive guide to building smart and reusable code in Java Rating: 0 out of 5 stars0 ratingsCODING INTERVIEWS: Advanced Guide to Help You Excel at Coding Interviews Rating: 0 out of 5 stars0 ratingsTest-Driven Development with React: Apply Test-Driven Development in Your Applications Rating: 0 out of 5 stars0 ratingsFull Stack Development with JHipster: Build modern web applications and microservices with Spring and Angular Rating: 0 out of 5 stars0 ratingsTesting Python: Applying Unit Testing, TDD, BDD and Acceptance Testing Rating: 4 out of 5 stars4/5Surviving the Whiteboard Interview: A Developer’s Guide to Using Soft Skills to Get Hired Rating: 5 out of 5 stars5/5Instant HTML5 Responsive Table Design How-to Rating: 0 out of 5 stars0 ratingsReact Deep Dive Rating: 5 out of 5 stars5/5Learning DevOps: The complete guide to accelerate collaboration with Jenkins, Kubernetes, Terraform and Azure DevOps Rating: 0 out of 5 stars0 ratingsTest-Driven Development with C++: A simple guide to writing bug-free Agile code Rating: 0 out of 5 stars0 ratingsDocker Cookbook: Over 100 practical and insightful recipes to build distributed applications with Docker Rating: 0 out of 5 stars0 ratingsThe Fragile Methodology Rating: 0 out of 5 stars0 ratings
Programming For You
Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsSQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5HTML in 30 Pages Rating: 5 out of 5 stars5/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Beginning Programming with C++ For Dummies Rating: 4 out of 5 stars4/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5Programming Arduino: Getting Started with Sketches Rating: 4 out of 5 stars4/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsC Programming For Beginners: The Simple Guide to Learning C Programming Language Fast! Rating: 5 out of 5 stars5/5C# Programming from Zero to Proficiency (Beginner): C# from Zero to Proficiency, #2 Rating: 0 out of 5 stars0 ratingsCoding with JavaScript For Dummies Rating: 0 out of 5 stars0 ratings
Reviews for Practical Test-Driven Development using C# 7
0 ratings0 reviews
Book preview
Practical Test-Driven Development using C# 7 - John Callaway
Practical Test-Driven Development using C# 7
Unleash the power of TDD by implementing real world examples under .NET environment and JavaScript
John Callaway
Clayton Hunt
BIRMINGHAM - MUMBAI
Practical Test-Driven Development using C# 7
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Amarabha Banerjee
Acquisition Editor: Shweta Pant
Content Development Editor: Aditi Gour
Technical Editor: Shweta Jadhav
Copy Editor: Safis Editing
Project Coordinator: Hardik Bhinde
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Graphics: Jason Monteiro
Production Coordinator: Aparna Bhagat
First published: February 2018
Production reference: 1090218
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78839-878-7
www.packtpub.com
mapt.io
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Why subscribe?
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
PacktPub.com
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Foreword
I'll be honest, when I first looked at the title of this book, Practical Test-Driven Development Using C# 7, I thought do we really need another book outlining the basics of unit testing and TDD?
I mean at this point, TDD isn't really that new, and plenty of authors have written about what TDD is and have given us countless examples of how to score a bowling or a tic-tac-toe game using TDD to drive the creation of the application.
The problems most developers run into when learning or trying to implement TDD is not understanding what TDD itself is and what red, green, refactor
means, but how to practically implement it in real-world situations. Most real-world applications are messy and don't conform easily to the usual TDD shoehorn that many well-meaning TDD books and examples try to demonstrate. The real difficulty in successfully implementing TDD arises when you try to use it to develop a non-trivial application—an application with databases and multiple layers and external services you need to call.
As a consultant, I spent a large amount of time teaching teams who were supposedly doing TDD how to actually do TDD. I saw countless examples of teams who would hardcode tests with fake data or call out directly to a database, because they didn't really understand what a mock was and how to isolate their tests. Moreover, I found many development teams that understood the basics of TDD, but didn't understand how to take business requirements and user stories and convert them into working unit tests that they can actually use to develop the system they were trying to create.
I've never had a difficult time teaching software developers the basics of TDD. It's fairly easy to explain how TDD works and how to get started doing it—and there have always been plenty of resources available to teach all that. No, what companies paid me the big bucks for was to sit down with their teams and explain all the nuances of TDD. What do you do when you have to mock a class that directly uses the database? How do you handle 15 test cases that have different input values but are essentially testing the same thing? Where do we start with TDD—which tests do we write first?
That's where Practical Test-Driven Development comes into the picture. For the first time ever, all that real tricky shit,
that I thought only I knew about and was esoteric and complicated to explain in a book, well it's explained—with plenty of examples—right here in the one you are holding.
When I first cracked open Practical Test-Driven Development, I was amazed. Not only did it explain the right concept of what TDD was (a design activity, not a testing one), and give an absolute beginner a step-by-step approach to learning and understanding TDD, but it took it far, far from there and showed you how to practically and pragmatically apply the concepts to a real-world, non-trivial application and did it in a way that didn't try and gloss over the messy stuff. Instead, Practical Test-Driven Development plows right into all the nooks and crannies of TDD and tells you exactly the kinds of problem you will encounter and how to get past them.
Here's the best part—you don't even have to know a thing about TDD to get huge value out of this book and become a better TDD practitioner than 90% of software developers who claim they are already doing TDD. Practical Test-Driven Development is laid out in such a way that it assumes that you don't know anything about TDD and shows you step-by-step, example-by-example, everything you need to know to go from complete beginner to expert in a way that I honestly didn't think was possible, until I sat down and read the book myself.
All in all, I am extremely happy with this book and I have a feeling I'm going to be recommending it as the go-to resources for learning TDD for many years to come. Every developer should be doing TDD and doing it the right way. Therefore, every developer should read this book.
John Sonmez
Founder, Simple Programmer
Contributors
About the authors
John Callaway, a Microsoft MVP, has been a professional developer since 1999. He has focused primarily on web technologies and has experience with everything from PHP to C# to ReactJS to SignalR. Clean code and professionalism are particularly important to him, along with mentoring and teaching others what he has learned along the way.
Clayton Hunt has been programming professionally since 2005, doing mostly web development with an emphasis on JavaScript and C#. He has a focus on Software Craftsmanship and is a signatory of both the Agile Manifesto and the Software Craftsmanship manifesto. He believes that through short iterations and the careful gathering of requirements, we can deliver the highest quality and most value in the shortest time. He enjoys learning and encouraging others to continuously improve themselves.
About the reviewer
Tomi Juhola is a versatile software development professional from Finland. He has wide experience, from embedded systems through distributed enterprise systems to a reinvention of IT in manufacturing in various roles. The key thing for him is to be agile and to help others grow.
Currently, he works in an industry-leading manufacturing company and is responsible for all things software and electric. He likes to spend his free time with new interesting development languages, technologies, and frameworks as well as with novel thoughts on organizations and personal growth.
I would like to thank my dear wife, Jonna, and daughter, Isla, for letting daddy reserve some time for reviewing. Love you both.
Packt is searching for authors like you
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Table of Contents
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Why TDD is Important
First, a little background
John's story on TDD
Clayton's story on TDD
So, what is TDD?
An approach to TDD
An alternative approach
The process
Red, green, and refactor
Coder's block
Why should we care?
Arguments against TDD
Testing takes time
Testing is expensive
Testing is difficult
We don't know how
Arguments in favor of TDD
Reduces the effort of manual testing
Reduces bug count
Ensures some level of correctness
Removes the fear of refactoring
A better architecture
Faster development
Different types of test
Unit tests
Acceptance tests
Integration tests
End to end tests
Quantity of each test type
Parts of a unit test
Arrange
Act
Assert
Requirements
Why are they important?
User stories
Role
Request
Reason
Gherkin
Givens
When
Then
Our first tests in C#
Growing the application with tests
Our first tests in JavaScript
Why does it matter?
Summary
Setting Up the .NET Test Environment
Installing the .NET Core SDK
Getting set up with VS Code
Downloading the IDE
Installing the VS Code
Adding extensions
Creating a project in VS Code
Setting up Visual Studio Community
Downloading Visual Studio Community
Installing Visual Studio Community
Switching to xUnit
Code katas
FizzBuzz
Creating the test project
The Given3ThenFizz test
The Given5ThenBuzz test
The Given15ThenFizzBuzz test
The Given1Then1 test
Theories
Solution to the FizzBuzz Problem
What is Speaker Meet?
Web API project
Listing Speakers (API)
Requirements
A new test file
Summary
Setting Up a JavaScript Environment
Node.js
What is Node?
Why do we need Node?
Installing Node
Linux
Mac OSX
Windows
NPM
What is NPM?
Why do we need NPM?
Installing NPM?
A quick introduction to JavaScript IDEs
Visual Studio Code
Why Visual Studio Code?
Installing Visual Studio Code
Linux
Mac
Windows
Installing the plugins you will need
Configuring the testing environment
WebStorm
Why WebStorm?
Installing WebStorm
Linux
Mac
Windows
Installing the plugins you will need
Configuring the testing environment
Create React App
What is Create React App?
Installing the global module
Creating a React application
Running the Create React App script
Mocha and Chai
Jest
Mocha
Chai
Sinon
Enzyme
Ejecting the React app
Configuring to use Mocha and Chai
A quick kata to check our test setup
The requirements
The execution
Starting the kata
Summary
What to Know Before Getting Started
Untestable code
Dependency Injection
Static
Singleton
Global state
Abstracting third-party software
Test doubles
Mocking frameworks
The SOLID principles
The Single Responsibility Principle
The Open/Closed principle
The Liskov Substitution principle
The Interface Segregation principle
The Dependency Inversion principle
Timely greeting
Fragile tests
False positives and false failures
Abstract DateTime
Test double types
Dummies
Dummy logger
Example in C#
Example in JavaScript
Stubs
Example in C#
Example in JavaScript
Spies
Example in C#
Example in JavaScript
Mocks
Example in C#
Example in JavaScript
Fakes
Example in C#
Example in JavaScript
N-Tiered example
Presentation layer
Moq
Business layer
Summary
Tabula Rasa – Approaching an Application with TDD in Mind
Where to begin
Yak shaving
Big design up front
A clean slate
One bite at a time
Minimum Viable Product
Different mindset
YAGNI – you aren't gonna need it
Test small
Devil's advocate
Test negative cases first
When testing is painful
A spike
Assert first
Stay organized
Breaking down Speaker Meet
Speakers
Communities
Conferences
Technical requirements
Summary
Approaching the Problem
Defining the problem
Digesting the problem
Epics, features, and stories; oh my!
Epics
Features
Stories
Maintain your backlog
The Speaker Meet problem
Meaningful separation
Speakers
Communities
Conferences
Separate by team function
Technical separations
Technical requirements
React web user interface
.NET Core
.NET Web API
Entity Framework
Azure
Database
An N-Tiered hexagonal architecture
Hexagonal architecture
Basic yet effective N-Tiered divisions
Service layer
Microservices
Data access layer
Repository Pattern
Generic repository
User interface adapter layer
User interface layer
Front-end business layer
Front-end user interface layer
Front-end data source layer
Testing direction
Back-to-front
Defining a data source
Creating a business layer
Building a user interface
Front-to-back
Defining a user interface
Creating a business layer
Building a data source
Inside out
Defining a business layer
Summary
Test-Driving C# Applications
Reviewing the requirements
Speaker listing
API
API tests
Moq
Testing exception cases
Service
Service tests
Clean tests
Repository
The IRepository interface
FakeRepository
Using factories with the FakeRepository
Soft delete
Speaker details
API
API tests
Service
Service tests
Clean the tests
More from the repository
Additional factory work
Testing exception cases
Summary
Abstract Away Problems
Abstracting away problems
Gravatar
Starting with an interface
Implementing a test version of the interface
Implementing the production version of the interface
Future planning
Abstracting the data layer
Extending the repository pattern
The Get method
The GetAll method
The Create method
The Delete method
The Update method
Ensuring functionality
Creating a speaker
Getting a single speaker
Getting multiple speakers
Updating a speaker
Deleting a speaker
Genericizing the repository
Step one – abstract interface
Step two – abstract the concrete class
Converting Create to a generic method
Converting Get to a generic method
Converting GetAll to a generic method
Converting Update to a generic method
Converting Delete to a generic method
Step three – reorient the tests to use the generic repository
InMemoryRepository Create tests
InMemoryRepository Get tests
InMemoryRepository GetAll tests
InMemoryRepository Update tests
Entity Framework
DbContext
Models
Generic repository
Dependency Injection
Wire it all up
Postman
Summary
Testing JavaScript Applications
Creating a React app
Ejecting the app
Configuring Mocha, Chai, Enzyme, and Sinon
The plan
Considering the React component
Looking at Redux testability
The store
Actions
Reducers
Unit-testing an API service
Speaker listing
A mock API service
The Get All Speakers action
Testing a standard action
Testing a thunk
The Get All Speakers reducer
The Speaker listing component
Speaker detail
Adding to the mock API Service
The Get Speaker action
The Get Speaker reducer
The Speaker Detail component
Summary
Exploring Integrations
Implementing a real API service
Replacing the mock API with the real API service
Using Sinon to mock Ajax responses
Fixing existing tests
Mocking the server
Application configuration
End-to-end integration tests
Benefits
Detriments
How much end-to-end testing should you do?
Configuring the API project
Integration test project
Where to begin?
Verifying the repository calls into the DB context
InMemory database
Adding speakers to the InMemory database
Verify that the service calls the DB through the repository
ContextFixture
Verify the API calls into the service
TestServer
ServerFixture
Summary
Changes in Requirements
Hello World
A change in requirements
Good evening
FizzBuzz
A new feature
Number not found
TODO app
Mark complete
Adding tests
Production code
But don't remove from the list!
Adding tests
Production code
Changes to Speaker Meet
Changes to the back-end
Changes to the front-end
Sorted by rating on client side
What now?
Premature optimization
Summary
The Legacy Problem
What is legacy code?
Why does code go bad?
When does a project become legacy?
What can be done to prevent legacy decay?
Typical issues resulting from legacy code
Unintended side effects
Open Closed Principle and legacy code
Liskov Substitution Principle and legacy code
Over-optimization
Overly clever code
Tight coupling to third-party software
Issues that prevent adding tests
Direct dependence on framework and third-party code
Law of Demeter
Work in the constructor
Global state
Static methods
Large classes and functions
Dealing with legacy problems
Safe refactoring
Converting values to variables
Extracting a method
Extracting a class
Abstracting third-party libraries and framework code
Early tests
Gold standard tests
Testing all potential outcomes
Moving forward
Fixing bugs
Free to do unsafe refactoring
Summary
Unraveling a Mess
Inheriting code
The game
A change is requested
Life sometimes hands you lemons
Getting started
Abstracting a third-party class
Unexpected Input
Making sense of the madness
Final beautification
Ready for enhancements
Summary
A Better Foot Forward
What we've covered
Moving forward
TDD is a personal practice
You don't need permission
Grow applications through tests
Introducing TDD to your team
Don’t force TDD on anyone
Gamification of TDD
Showing your team the benefits
Review the results
Rejoining the world as a TDD expert
Seek a mentor
Becoming a mentor
Practice, practice, practice
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Preface
As software projects grow in size and complexity, it can often become more difficult, time-consuming, and expensive to maintain them. Through Test Driven Development (TDD), you can learn to develop testable, extensible, and maintainable software applications.
Who this book is for
This book is for software developers who have cursory knowledge of TDD and are looking to gain a thorough understanding of how TDD can benefit them and the applications they produce. Software developers with an intermediate understanding of C# and the .NET Framework and/or a thorough understanding of JavaScript and React will likely be able to follow along with all the code examples used throughout the book.
What this book covers
The book covers everything from why TDD is important to setting up testing environments, and how to get started testing a green-field application. As the reader grows more comfortable, they will be exposed to more advanced TDD topics such as abstracting away third-party code, approaching a problem from a TDD perspective, and how to deal with legacy code that wasn't written with testability in mind.
Chapter 1, Why TDD is Important, asks what is TDD and why should you care? In this chapter, you will learn what TDD is and why it matters. A compelling argument for TDD will be made and the benefits, and more importantly, the execution will be shown.
Chapter 2, Setting Up the .NET Test Environment, explains how to set up your IDE and configure the testing framework so that you can easily run your tests in C# and .NET, with more detail and many more examples of growing complexity in the Speaker Meet API.
Chapter 3, Setting Up a JavaScript Environment, configures the JavaScript testing framework so that you can easily run your tests in your IDE. It provides more detail and many more examples of growing complexity in the Speaker Meet React application.
Chapter 4, What to Know Before Getting Started, dives deeper into the why and how of TDD. you will learn the importance of defining and testing boundaries and abstracting away third-party code (including the .NET Framework), and you'll discover more advanced concepts such as spies, mocks, and fakes, and how to avoid pitfalls along the way.
Chapter 5, Tabula Rasa - Approaching an Application with TDD in Mind, explains how to get started with a new application. You'll apply what you've learned in the previous chapters and take the same approach with a full-sized application using Speaker Meet as an example.
Chapter 6, Approaching the Problem, takes the broader problem of the overall application and breaks it into meaningful chunks that can be developed independently. You'll learn different approaches to developing an application, such as front to back, back to front, and inside out.
Chapter 7, Test-Driving C# Applications, takes requirements and assembled user stories and turns them into working software using TDD. It explains how to utilize all the skills you've assembled so far to test the boundaries, testing small, individual units.
Chapter 8, Abstract Away Problems, explores abstracting away third-party libraries, including the .NET Framework. It covers removing dependencies on things such as DateTime and Entity Framework. It explains how to decouple their application from specific implementations to not only allow your application to be testable but much more flexible and easy to modify in the future.
Chapter 9, Testing JavaScript Applications, now that you have a working API, focuses on creating a Single Page Application in JavaScript using React. It focuses on test-driven actions and reducers and any functionality within the application.
Chapter 10, Exploring Integrations, explains how to write integration tests to ensure that your application is functioning properly.
Chapter 11, Changes in Requirements, focuses on what happens when the requirements change. What happens if a bug is discovered? No problem, change a test or write a new one to cover the new requirement or to defend against the discovered bug. Now, write some new code or change some existing code to make all of the new/modified tests pass. If you do everything correctly, you should feel safe to make these changes as your existing test suite will prevent you from introducing new bugs.
Chapter 12, The Legacy Problem, explains that there are a lot of applications out there without sufficient (any?) test coverage, and even fewer were written test-first. You'll discover some of the major problems with legacy applications that weren't written with testability in mind; they will be identified, and also how best to recover will be covered.
Chapter 13, Unraveling a Mess, dives into how to go about safely modifying a legacy application that wasn't written with testing in mind. How can you add tests to minimize the potential for introducing new bugs when modifying the existing code? An extreme example will be used to explore these topics and more.
Chapter 14, A Better Foot Forward, emphasizes that TDD is a personal choice. You don't need anyone's permission to do good work. Advice on how to continue a successful journey of TDD, how to introduce TDD to your team, and how to rejoin the world as a TDD expert will be covered in this chapter.
To get the most out of this book
Readers wanting to follow along with the examples in the book should have the following:
An intermediate understanding of C# and/or JavaScript
Prior exposure to React will be beneficial though not required
Familiarity with N-tier architecture
Download the example code files
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at www.packtpub.com.
Select the SUPPORT tab.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Practical-Test-Driven-Development. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Download the color images
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://www.packtpub.com/sites/default/files/downloads/PracticalTestDrivenDevelopment_ColorImages.pdf.
Conventions used
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system.
A block of code is set as follows:
babel
: {
presets
: [
react-app
]
},
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
[default]
exten => s,1,Dial(Zap/1|30)
exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)
Any command-line input or output is written as follows:
>npm install mocha chai sinon enzyme
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: Select System info from the Administration panel.
Warnings or important notes appear like this.
Tips and tricks appear like this.
Get in touch
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Reviews
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
Why TDD is Important
You've picked up this book because you want to learn more about Test-Driven Development (TDD). Maybe you've heard the term before. Perhaps you've known software developers who write unit tests and want to learn more. We'll introduce you to the terms, the structure, and the ideology around TDD. By the end of this book, you'll have sufficient knowledge to re-enter the world as a Test-Driven Developer and feel confident about using your skills throughout your long and prosperous career.
Why this book? Certainly, there are many other books on the topic of TDD. We have written this book with the hope that it provides you, the reader, with low-level insight into the mindset we use when doing TDD. We also hope that this book provides an updated view of some of the concepts and lessons we have learned while doing TDD over the last 10 years.
So, why is TDD so important? As more businesses and industries rely on software solutions, it's increasingly important that those solutions be robust and error-free. The cheaper and more consistent, they are the better. Applications developed with TDD in mind are inherently more testable, easier to maintain, and demonstrate a certain level of correctness not easily achieved otherwise.
In this chapter, we will gain an understanding of:
Defining TDD and exploring the basics
Creating our first tests in C# and JavaScript
Exploring the basic steps of Red, Green, Refactor
Growing complexity through tests
First, a little background
It's possible that you've had some exposure to unit tests in your career. It's highly likely that you've written a test or two. Many developers, unfortunately, haven't had the opportunity to experience the joys of Test-Driven Development.
John's story on TDD
I was first introduced to TDD about five years ago. I was interviewing for a lead developer position for a small startup. During the interview process, the CTO mentioned that the development team was practicing TDD. I informed him that I didn't have any practical TDD experience, but that I was sure I could adapt.
In all honesty, I was bit nervous. Up to that point, I had never even written a single unit test! What had I gotten myself into? An offer was extended and I accepted. Once I joined the small company I was told that, while TDD was the goal, they weren't quite there yet. Phew; crisis averted. However, I was still intrigued. It wasn't until a few months later that the team delved into the world of TDD, and the rest, as they say, is history.
Clayton's story on TDD
My introduction to TDD is a little different from John's. I have been writing code since I was in middle school in the early 1990s. From then until 2010, I always struggled with writing applications that didn't require serious architectural changes when new requirements were introduced. In 2010, I finally got fed up with the constant rewrites and began researching tools and techniques to help me with my problem. I quickly found TekPub, an e-learning site that was, at the time, owned and operated by Rob Conery. Through TekPub I began learning the SOLID principles and TDD. After banging my head against the wall for close to six months, I started to grasp what TDD was and how I could use those principles. Coupled with the SOLID principles, TDD helped me to write easy to understand code that was flexible