Preface

Many years ago, I started avoiding cookbook-style books when I wanted to learn a new technology or develop a new skill. A book should guide us to understand fundamental ideas so we can adapt our learning to fit our needs. We should not get lost just because a recipe doesn’t match exactly what we want to accomplish.

I also tend to avoid books that are full of theory. You probably know what I mean. Instead of explaining how to use a technology, these books mention ideas with no exploration of putting the ideas into practice. Focusing on either one of these two tangents can leave the learning experience incomplete.

This book is different. Instead of giving you a few simple examples like a cookbook or droning on with rules and definitions, I’ll show you how to use tests to write software that does the following:

  • What users expect and with ease
  • Let’s you add new features without breaking what you’ve already done
  • Clearly communicates what the code does

We’re going to start from the beginning and build multiple projects. You’ll learn what a test is and how it can help by building an easy and natural way to write tests in C++. This is called Test-Driven Development (TDD) and you’ll be using TDD to develop the tools needed for your projects.

In order to get the most benefit from TDD, you’ll need a way to write and run tests. Some programming languages already support TDD while C++ needs extra tools and libraries to support tests. I could have simply explained how to use various TDD tools that already exist. That would be a cookbook approach because each existing solution is slightly different. By starting from the beginning and building what you’ll need, you’ll learn TDD and at the same time you’ll learn how all the other solutions work. The concepts are the same.

For example, most people who learn how to drive a car will be able to drive a pickup truck or a van. Some minor differences are expected but the concepts are the same. Riding a motorcycle is more of a challenge but many of the same concepts are still valid. Driving a bus might need some extra training but is also similar.

If you decide to use other tools or even other languages, you’ll gain a deep understanding of how those other tools work by following the steps in this book. The other tools will be like driving a pickup truck.

This book is divided into three parts. You’ll build a testing library in the first part that will let you write and run tests. You’ll learn how to proceed one step at a time and let the tests guide you.

The second part will use the testing library to start a new project to help you log messages as your software runs. This is a logging library and this project will show you how to build software that meets the needs of your intended customer. You’ll be adding many features to the logging library and you’ll learn how to keep everything working while developing more features.

The intended customer for the logging library is a C++ micro-services developer and this customer focus extends into the third part where you’ll extend the testing library and build a simple service. The service will be used to explain one of the most difficult aspects of software development how to test multiple threads.

All three parts will combine to show you how to use TDD to effectively design and write software that meets the customers needs, gives you the confidence to make changes, and lets other team members understand the design.

Who this book is for

This book is for C++ developers already familiar with and using C++ for daily tasks. You don’t need to be an expert, but you should already know some modern C++ and how to use templates to get the most out of this book.

If you’ve ever struggled to add a new feature to a large project without breaking the software in other places, then this book can help. You’ll become a better software developer and avoid the stress and worry of fixing bugs or making design changes. TDD is a process that will guide you to create intuitive designs that your users will understand and enjoy.

If you’ve ever hesitated over making an improvement and decided to keep an outdated and confusing design that nobody wants to touch because it might break, then this book can help. Maybe you have a good idea but you know your manager will never agree because the risk is too high. If your project is following TDD practices that this book explains, then you can feel more confident about making improvements. You can let the tests prove your idea is solid.

Do you have new team members who need to quickly understand how your software works? The process that this book explores will help you write tests in TDD that will document the software design and requirements. You might even find that the tests help your own understanding especially when returning to a project that you haven’t worked on in a long time.

C++ is a language with a lot of power and details to consider. This book helps to simplify the software development process through TDD. Even if you already know how to use one or more TDD tools, this book will improve your skills and give you the confidence to apply TDD in more advanced or larger projects.

What this book covers

Chapter 1, Desired Test Declaration, uses C++ to write your first test starting from an empty project.

Chapter 2, Test Results, reports and uses test results so that you can quickly know what parts of a project are working and what parts are failing.

Chapter 3, The TDD Process, uses TDD on purpose by identifying the steps you’ve already been doing.

Chapter 4, Adding Tests to a Project, enhances tests to pass or fail based on whether your expectations are being met.

Chapter 5, Adding More Confirm Types, makes tests more capable by giving you the power to check any value types to see if they meet expectations.

Chapter 6, Explore Improvements Early, looks for other improvements and shows you how to step back and explore ideas you might not have thought of up to this point.

Chapter 7, Test Setup and Teardown, prepares tests to run and the cleanup afterward so that you can focus tests on what they need to do which helps make the tests easier to understand.

Chapter 8, What Makes a Good Test?, provides advice and learning from other chapters to reinforce what you’ve learned so far and encourages you to continue with hints of topics in later chapters.

Chapter 9, Using Tests, builds a logging library that puts everything you’ve learned so far into practical use.

Chapter 10, The TDD Process in Depth, practices using TDD to add features to a growing project including how to handle design changes.

Chapter 11, Managing Dependencies, adds features that can be exchanged, showing you how to test unreliable software components and how to make progress even when you don’t have all the components that you need.

Chapter 12, Creating Better Test Confirmations, uses Hamcrest matchers to improve tests by letting you verify expectations more naturally.

Chapter 13, How To Test Floating Point and Custom Values, shows how to reliably use floats and how to extend Hamcrest matchers to meet custom needs.

Chapter 14, How To Test Services, covers how services are different and how to test services.

Chapter 15, How To Test With Multiple Threads, simplifies and coordinates tests with multiple threads so that you can avoid race conditions while testing every possible thread interaction reliably and predictably.

To get the most out of this book

You will need a modern C++ compiler capable of building C++20 or later code. Everything in this book uses standard C++ and will run on any computer. All output is text.

This book lets you build the code with whatever build system you are most comfortable using. The projects all have few files with simple folder structures. You can easily create a project in your code editor and follow along.

This book does not describe finished projects. Each project is a journey. The first chapter starts with an empty project and each subsequent chapter adds to the code already created in previous chapters. You’re encouraged to follow along.

Remember to study the process. This is more important than the actual code that each chapter explains. The TDD process is mentioned many times in this book. The first few chapters introduce you to TDD until there are enough features available in the testing library so that the testing library can be used to build another project. The second logging library project explores the TDD process in more depth and detail. Once the logging library is usable, then both the testing and logging libraries are used to build a simple service project. There is a pattern to the TDD process that repeats. Learning the TDD process through each of the projects will give you the most benefit.

Because the projects are built step by step, you can also benefit from the mistakes explained along the way. Sometimes, the designs will change, and you can benefit from the reasons for the changes as well as learn how to manage the changes.

When I say that you need a C++20 compiler, that’s a simplification. There are many different features of C++ that compiler vendors support in different versions of their compilers. A good rule to follow is to make sure that your compiler supports concepts in C++20. We use concepts in the final chapters of this book and if your compiler supports concepts, then you should have everything you need. A good link to read more is:

https://en.cppreference.com/w/cpp/compiler_support

When you visit the link, scroll down to the C++20 section and look for the row that identifies the concepts feature. At the time of writing, the following compilers should work:

  • GCC version 10
  • Clang version 10
  • MSVC version 19.30
  • Apple Clang version 12 (however, this compiler only has a partial implementation)

You’ll likely be able to use whatever version of the C++ Standard Library that comes with your compiler. However, another good rule that should work is to make sure that your Standard Library also supports concepts. At the time of writing, the following Standard Libraries should work:

  • GCClibstdc++ version 10
  • Clang libc++ version 13
  • MSVC STL version 19.23
  • Apple Clang version 13.1.6

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Test-Driven-Development-with-CPP. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

Code in text: 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: “That’s why the confirm macros we have now are called CONFIRM_TRUE and CONFIRM_FALSE.”

A block of code is set as follows:

TEST("Test bool confirms")
{
    bool result = isNegative(0);
    CONFIRM_FALSE(result);
    result = isNegative(-1);
    CONFIRM_TRUE(result);
}

Any command-line input or output is written as follows:

Running 3 tests

---------------

Test can be created

Passed

---------------

Test with throw can be created

Passed

---------------

Test that never throws can be created

Failed

Expected exception type int was not thrown.

---------------

Tests passed: 2

Tests failed: 1

Program ended with exit code: 1

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “We’ll just change the status from Failed to Expected failure.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

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/support/errata and fill in the form.

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.

Share Your Thoughts

Once you’ve read Test Driven Development with C++, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere? Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application. 

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

  1. Scan the QR code or visit the link below

https://packt.link/free-ebook/9781803242002

  1. Submit your proof of purchase
  2. That’s it! We’ll send your free PDF and other benefits to your email directly
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.103.209