6 Test-driven development and dependency injection

 

This chapter covers

  • Using locks, mutexes, and semaphores
  • Converting between synchronous and asynchronous methods
  • Using dependency injection with unit tests

In chapters 3 and 4, we looked at the codebase we inherited and discussed potential improvements. To solve the issues we found, we started a new version of the Flying Dutchman Airlines service and implemented the database access layer with Entity Framework Core in chapter 5. In this chapter, we’ll start implementing the business logic by moving into the repository layer and creating the CustomerRepository class. Figure 6.1 shows where we are in the scheme of the book.

Figure 6.1 After having implemented the database access layer in chapter 5, we’ll move on to implementing the CustomerRepository in this chapter.

The repository layer is the meat and potatoes of our service. In the repository layer we do the following two things:

  1. Query and manipulate the database by communicating with the database access layer
  2. Return the requested entities or information to the service layer

We want to create isolated, small, clean, and readable methods that follow the single-responsibility principle (SRP). Following the SRP makes it easier to test and maintain our code because we can quickly understand every method and fix any potential bugs.

6.1 Test-driven development

Exercises

6.2 The CreateCustomer method

6.2.1 Why you should always validate input arguments

6.2.2 Using “arrange, act, assert” to write unit tests

6.2.3 Validating against invalid characters

6.2.4 In-lining test data with the [DataRow] attribute

6.2.5 Object initializers and autogenerated code

6.2.6 Constructors, reflection, and asynchronous programming

6.2.7 Locks, mutexes, and semaphores