Home > Articles

  • Print
  • + Share This
This chapter is from the book

Building Services Test First

It’s pretty easy to talk about TDD, but, despite countless blogs and books extolling its virtues, it is still pretty rare to find people who practice it regularly. It is even rarer still to find people who practice it without cutting corners. Cutting corners in TDD is the worst of both worlds—you’re spending the time and effort on TDD but you’re not reaping the benefits of code quality and functional confidence.

In this section of the chapter, we’re going to write a method for our service in test-first fashion. If we’re doing it right, it should feel like we’re spending 95% of our time writing tests, and 5% of our time writing code. The size of our test should be significantly larger than the size of the code we’re testing. Some of this just comes from the fact that it takes more code to exercise all possible paths through a function under test than it does to write the function itself. For more details on this concept, check out the book Continuous Delivery by Jez Humble & David Farley.

Many organizations view the effort to write tests as wasteful, claiming that it does not add value and actually increases time-to-market. There are a number of problems with this myopic claim.

It is true that TDD will, indeed, slow initial development. However, let’s consider a new definition of the term development:

  • development(n) : The period where the features of the application are being added without the so-called burden of a running version of it in production.

  • Dan Nemeth

With this definition in mind when we look at the entire life cycle of an application, only for a very small portion of that time is the application ever in this state of “development”.

Investment in testing will pay dividends throughout the entire life cycle of the application, but especially in production where:

  • Uptime is a must.

  • Satisfying change/feature requests is urgent.

  • Debugging is costly, difficult, and oftentimes approaching impossible.

To get started on our own TDD journey of service creation, let’s create a file called handlers_test.go (shown in Listing 5.4). This file is going to test functions written in the handlers.go file. If your favorite text editor has a side-by-side or split-screen mode, this would be a great time to use it.

We’re going to be writing a test for the HTTP handler invoked when someone POSTs a request to start a new match. If we check back with our Apiary documentation, we’ll see that one of the requirements is that this function return an HTTP status code of 201 (Created) when successful.

Let’s write a test for this. We’ll call the function TestCreateMatch and, as with all Go unit tests using the basic unit testing package, it will take as a parameter a pointer to a testing.T struct.

Creating a First, Failing Test

In order to test our server’s ability to create matches, we need to invoke the HTTP handler. We could invoke this manually by fabricating all of the various components of the HTTP pipeline, including the request and response streams, headers, etc. Thankfully, though, Go provides us with a test HTTP server. This doesn’t open up a socket, but it does all the other work we need it to do, which lets us invoke HTTP handlers.

There is a lot going on here, so let’s look at the full listing (Listing 5.4) for the test file in our first iteration, which, in keeping with TDD ideology, is a failing test.

Listing 5.4 handlers_test.go

package main

import (


var (
        formatter = render.New(render.Options{
                IndentJSON: true,

func TestCreateMatch(t *testing.T) {
        client := &http.Client{}
        server := httptest.NewServer(
        defer server.Close()

        body := []byte("{\n  \"gridsize\": 19,\n  \"players\": [\n    {\n
        \"color\": \"white\",\n      \"name\": \"bob\"\n    },\n    {\n
        \"color\": \"black\",\n      \"name\": \"alfred\"\n    }\n  ]\n}")

        req, err := http.NewRequest("POST",
                server.URL, bytes.NewBuffer(body))
        if err != nil {
                t.Errorf("Error in creating POST request for createMatchHandler: %v",
        req.Header.Add("Content-Type", "application/json")

        res, err := client.Do(req)
        if err != nil {
                t.Errorf("Error in POST to createMatchHandler: %v", err)

        defer res.Body.Close()

        payload, err := ioutil.ReadAll(res.Body)
        if err != nil {
                t.Errorf("Error reading response body: %v", err)

        if res.StatusCode != http.StatusCreated {
                t.Errorf("Expected response status 201, received %s",

        fmt.Printf("Payload: %s", string(payload))

Here’s another reason why we like Apiary so much: if you go to the documentation for the create match functionality and click on that method, you’ll see that it can actually generate sample client code in Go. Much of that generated code is used in the preceding test method in Listing 5.3.

The first thing we do is call httptest.NewServer, which creates an HTTP server listening at a custom URL that will serve up the supplied method. After that, we are using most of Apiary’s sample client code to invoke this method.

We have two main assertions here:

  • We do not receive any errors when executing the request and reading the response bytes

  • The response status code is 201 (Created).

If we were to try and run the test above, we would get a compilation failure. This is true TDD, because we haven’t even written the method we’re testing (createMatchHandler doesn’t exist yet). To get the test to compile, we can add a copy of our original scaffold test method to our handlers.go file as shown in Listing 5.5:

Listing 5.5 handlers.go

package main

import (


func createMatchHandler(formatter *render.Render) http.HandlerFunc {
        return func(w http.ResponseWriter, req *http.Request) {
                 struct{ Test string }{"This is a test"})

Now we can see what happens when we try and test this. First, to test we issue the following command:

$ go test -v $(glide novendor)

We should see the following output:

Expected response status 201, received 200 OK

Now we’ve written our first failing test! At this point, some of you may be starting to doubt these methods. If so, please bear with us; we promise that by the end of the chapter you will have seen the light.

Let’s make this failing test a passing one. To make it pass, all we do is make the HTTP handler return a status of 201. We don’t write the full implementation, we don’t add complex logic. The only thing we do is make the test pass. It is vitally important to the process that we only write the minimum code necessary to make the test pass. If we write code that isn’t necessary for the test to pass, we’re no longer in test-first mode.

To make the test pass, change the formatter line in handlers.go to as follows:

formatter.JSON(w, http.StatusCreated, struct{ Test string }{"This is a test"})

We just changed the second parameter to http.StatusCreated. Now when we run our test, we should see something similar to the following output:

$ go test -v $(glide novendor)
=== RUN   TestCreateMatch
--- PASS: TestCreateMatch (0.00s)
ok      github.com/cloudnativego/gogo-service    0.011s

Testing the Location Header

The next thing that we know our service needs to do in response to a create match request (as stated in our Apiary documentation) is to set the Location header in the HTTP response. By convention, when a RESTful service creates something, the Location header should be set to the URL of the newly created thing.

As usual, we start with a failing test condition and then we make it pass.

Let’s add the following assertion to our test:

if _, ok := res.Header["Location"]; !ok {
  t.Error("Location header is not set")

Now if we run our test again, we will fail with the above error message. To make the test pass, modify the createMatchHandler method in handlers.go to look like this:

func createMatchHandler(formatter *render.Render) http.HandlerFunc {
        return func(w http.ResponseWriter, req *http.Request) {
                w.Header().Add("Location", "some value")
                formatter.JSON(w, http.StatusCreated,
                       struct{ Test string }{"This is a test"})

Note that we didn’t add a real value to that location. Instead, we just added some value. Next, we’ll add a failing condition that tests that we get a valid location header that contains the matches resource and is long enough so that we know it also includes the GUID for the newly created match. We’ll modify our previous test for the location header so the code looks like this:

        loc, headerOk := res.Header["Location"]
        if !headerOk {
                t.Error("Location header is not set")
        } else {
                if !strings.Contains(loc[0], "/matches/") {
                        t.Errorf("Location header should contain '/matches/'")
                if len(loc[0]) != len(fakeMatchLocationResult) {
                        t.Errorf("Location value does not contain guid of new match")

We’ve also added a constant to the test called fakeMatchLocationResult, which is just a string that we also pulled off of Apiary representing a test value for the location header. We’ll use this for test assertions and fakes. This is defined as follows:

const (
   fakeMatchLocationResult = "/matches/5a003b78-409e-4452-b456-a6f0dcee05bd"

Epic Montage—Test Iterations

Since we have limited space in this book, we don’t want to dump the code for every single change we made during every iteration where we went from red (failing) to green (passing) light in our testing.

Instead, we’ll describe what we did in each TDD pass we made:

  • Wrote a failing test.

  • Made the failing test pass.

  • Checked in the results.

If you want to examine the history so you can sift through the changes we made line-by-line, check out the commit history in GitHub. Look for commits labelled “TDD GoGo service Pass n” where n is the testing iteration number.

We’ve summarized the approaches we took for each failed test and what the resolution was to make the test pass in the following list of steps, so cue up your favorite Hollywood hacker movie montage background music and read on:

  1. TDD Pass 1. We created the initial setup required to host a test HTTP server that invokes our HTTP handler method (the method under test). This test initially failed because of compilation failure—the method being tested did not yet exist. We got the test to pass by dumping the test resource code into the createMatchHandler method.

  2. TDD Pass 2. Added an assertion that the result included a Location header in the HTTP response. This test initially failed, so we added a placeholder value in the location header.

  3. TDD Pass 3. Added an assertion that the Location header was actually a properly formatted URL pointing at a match identified by a GUID. The test initially failed, so we made it pass by generating a new GUID and setting a proper location header.

  4. TDD Pass 4. Added an assertion that the ID of the match in the response payload matched the GUID in the location header. This test initially failed and, to make it pass, we had to add code that un-marshaled the response payload in the test. This meant we actually had to create a struct that represented the response payload on the server. We stopped returning “this is a test” in the handler and now actually return a real response object.

  5. TDD Pass 5. Added an assertion that the repository used by the handler function has been updated to include the newly created match. To do this, we had to create a repository interface and an in-memory repository implementation.

  6. TDD Pass 6. Added an assertion that the grid size in the service response was the same as the grid size in the match added to the repository. This forced us to create a new struct for the response, and to make several updates. We also updated another library, gogo-engine, which contains minimal Go game resolution logic that should remain mostly isolated from the service.

  7. TDD Pass 7. Added assertions to test that the players we submitted in the new match request are the ones we got back in the service JSON reply and they are also reflected accordingly in the repository.

  8. TDD Pass 8. Added assertions to test that if we send something other than JSON, or we fail to send reasonable values for a new match request, the server responds with a Bad Request code. These assertions fail, so we went into the handler and added tests for JSON un-marshaling failures as well as invalid request objects. Go is pretty carefree about JSON de-serialization, so we catch most of our “bad request” inputs by checking for omitted or default values in the de-serialized struct.

Let’s take a breather and look at where things stand after this set of iterations. Listing 5.6 shows the one handler that we have been developing using TDD, iterating through successive test failures which are then made to pass by writing code. To clarify, we never write code unless it is in service of making a test pass. This essentially guarantees us the maximum amount of test coverage and confidence possible.

This is a really hard line for many developers and organizations to take, but we think it’s worth it and have seen the benefits exhibited by real applications deployed in the cloud.

Listing 5.6 handlers.go (after 8 TDD iterations)

package service

import (


func createMatchHandler(formatter *render.Render, repo matchRepository)
     http.HandlerFunc {
        return func(w http.ResponseWriter, req *http.Request) {
          payload, _ := ioutil.ReadAll(req.Body)
          var newMatchRequest newMatchRequest
          err := json.Unmarshal(payload, &newMatchRequest)
          if err != nil {
            formatter.Text(w, http.StatusBadRequest,
              "Failed to parse create match request")
          if !newMatchRequest.isValid() {
            formatter.Text(w, http.StatusBadRequest,
              "Invalid new match request")

          newMatch := gogo.NewMatch(newMatchRequest.GridSize,
            newMatchRequest.PlayerBlack, newMatchRequest.PlayerWhite)
          w.Header().Add("Location", "/matches/"+newMatch.ID)
          formatter.JSON(w, http.StatusCreated,
            &newMatchResponse{ID: newMatch.ID,
                       GridSize: newMatch.GridSize,
                        PlayerBlack: newMatchRequest.PlayerBlack,
                       PlayerWhite: newMatchRequest.PlayerWhite})

While Go’s formatting guidelines generally call for an 8-character tab, we’ve condensed some of that to make the listing a little more readable here.

We have about 20 lines of code in a single function, and we have about 120 lines of code in the two test methods that exercise that code. This is exactly the type of ratio we want. Before we even open a single HTTP test tool to play with our service, we want to have 100% confidence and know exactly how our service should behave.

Based on the tests that we’ve written thus far, and the code in Listing 5.6, can you spot any testing gaps? Can you see any scenarios or edge cases that might trip up our code that we have not yet accounted for in testing?

There are two glaring gaps that we see:

  1. This service is not stateless. If it goes down, we lose all of our in-progress games. This is a known issue, and we’re willing to let it slide because we have a crystal ball, and we know that Chapter 7 will address data persistence.

  2. There are a number of abuse scenarios against which we are not guarding. Most notably, there is nothing to stop someone from rapidly creating game after game until we exceed our memory capacity and the service crashes. This particular abuse vector is a side-effect of us storing games in memory and us violating a cardinal rule of cloud native: statelessness. We’re not going to write tests for this either because, as mentioned in #1, these conditions are temporary and writing DDoS-guarding code is a rabbit hole we want to avoid in this book.

We’ll correct some of these as we progress throughout the book, but others, like guarding against all of the edge cases, are really going to be your responsibility as you build production-grade services.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020