chapter two

2 Getting started with testing

 

This chapter covers

  • Basics of unit testing
  • Basics of Go testing framework
  • Writing idiomatic tests and code in Go
  • Adding a URL parser package to the Go Standard Library

Let’s go back 13 years. The Go team at Google is busy writing the Go Standard Library. You, the programmer, recently joined the team. At Google, other developers in a team called the Wizards are working on a redirection service.

When their program receives a web request, they check the URL to see if it's valid, and if the URL is valid, they want to change some parts of it and redirect the web request to a new location. But they realized that there isn't a URL parser in the Go Standard Library.

So they asked you to add such a URL parser package to the Go Standard Library. You know the basics but don't yet know how to write and test idiomatic code in Go. I'll work throughout the chapter to help you write idiomatic code by implementing and unit testing a new library package called url from scratch.

Figure 2.1 Parsing a URL
  1. Parse a URL to check whether it's a valid URL
  2. Separate the URL into its parts: Scheme, host, and path
  3. Provide an ability to change the parts of a parsed URL

2.1 Go's testing approach

2.1.1 What is a "unit" in Go?

2.1.2 What is a unit test?

2.1.3 Wrap up

2.2 Writing your first unit test

2.2.1 Creating the url package

2.2.2 Creating a test file

2.2.3 Writing a test function

2.2.4 Testing by signals

2.2.5 Wrap up

2.3 Writing a URL parser

2.3.1 Parsing the scheme

2.3.2 Parsing the hostname

2.3.3 Parsing the path

2.3.4 Wrap up

2.4 Summary