Bitpath

Lesson 2 · Unit 07

Tests, JSON and generics

Check your code with tests, exchange data as JSON, and write one function for several types.

13 exercisesabout 3 min

What you practise

  • Table-driven tests, JSON to and from structs with field tags, a generic function with a constraint

Try a question from this lesson

Pick one

This function should turn a number positive: -3 becomes 3. Instead of checking by eye, the program checks itself. What prints?

Go
func Abs(n int) int {
  if n < 0 {
    return n
  }
  return n
}

if Abs(-3) != 3 {
  fmt.Println("FAIL")
} else {
  fmt.Println("ok")
}
Hint

Follow -3 through the function. Which return does it reach, and with what value?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Tests

Go has testing built in. A test lives in a file whose name ends in _test.go, in a function named Test plus something, taking t *testing.T.

The test calls your code and compares the result with what you expect. t.Errorf reports a failure, formatted like Printf.

The command go test runs every test in the package and reports PASS or FAIL.

Go
// in the file abs_test.go
func TestAbs(t *testing.T) {
  got := Abs(-3)
  if got != 3 {
    t.Errorf("Abs(-3) = %d, want 3", got)
  }
}

Concept

Table-driven tests

To test many inputs, write a table: a slice with one row per case, each row an input and the wanted result. One loop checks every row.

[]struct{ in, want int }{...} is a slice of a small struct that is declared right there, without a name.

Adding a test case is adding one line. This is the usual shape of a Go test.

Go
func TestAbs(t *testing.T) {
  tests := []struct{ in, want int }{
    {5, 5}, {-2, 2}, {0, 0},
  }
  for _, tc := range tests {
    got := Abs(tc.in)
    if got != tc.want {
      t.Errorf("Abs(%d) = %d, want %d",
        tc.in, got, tc.want)
    }
  }
}

Concept

JSON

JSON is a text format for data that nearly every program and website understands.

json.Marshal turns a struct into JSON. The tag after each field, written between backticks, gives the name to use in the JSON. Only exported fields are included.

Marshal returns bytes and an error; string(data) turns the bytes into text.

Go
type Item struct {
  Name  string `json:"name"`
  Price int    `json:"price"`
}

it := Item{Name: "tea", Price: 4}
data, err := json.Marshal(it)
if err != nil {
  fmt.Println("cannot encode:", err)
}
fmt.Println(string(data))
// {"name":"tea","price":4}

9 more exercises in the app

  • 1× true or false
  • 2× fill the blanks
  • 4× type the answer
  • 2× multiple choice

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy