8 Writing tests for microservices

 

This chapter covers

  • Writing good automated tests
  • Understanding the test pyramid and how it applies to microservices
  • Testing microservices from the outside
  • Writing fast, in-process tests for endpoints
  • Using Microsoft.AspNetCore.TestHost for integration and unit tests

Up to this point, we’ve written a few microservices and set up collaborations between some of them. The implementations are fine, but we haven’t written any tests for them. As we write more and more microservices, developing systems without good automated tests becomes unmanageable. In the first half of this chapter, I’ll discuss what you need to test for each individual microservice. Then we’ll dive into code, looking first at testing endpoints in isolation, and then at testing a complete microservice as if you were sending it requests from another microservice, but in-process using the TestServer from the Microsoft.AspNetCore.TestHost library.

8.1 What and how to test

In chapter 1, you saw three characteristics of a microservice that make it good for continuous delivery:

8.1.1 The test pyramid: What to test in a microservices system

8.1.2 System-level tests: Testing a complete microservice system end to end

8.1.3 Service-level tests: Testing a microservice from outside its process

8.1.4 Unit-level tests: Testing endpoints from within the process

8.2 Testing libraries: Microsoft.AspNetCore.TestHost and xUnit

8.2.1 Meet Microsoft.AspNetCore.TestHost

8.2.2 Meet xUnit

8.2.3 xUnit and Microsoft.AspNetCore.TestHost working together

8.3 Writing unit tests using Microsoft.AspNetCore.TestHost

8.3.1 Setting up a unit-test project

8.3.2 Using the TestServer and HttpClient to unit-test endpoints

8.3.3 Injecting mocks into endpoints

8.4 Writing service-level tests

8.4.1 Creating a service-level test project

8.4.2 Creating mocked endpoints

8.4.3 Executing the test scenario against the microservice under test

Summary